back to the lesson

The sibling question

importance: 5

If elem – is an arbitrary DOM element node…

  • Is it true that elem.lastChild.nextSibling is always null?
  • Is it true that elem.children[0].previousSibling is always null ?
  1. Yes, true. The element elem.lastChild is always the last one, it has no nextSibling, so if there are children, then yes.
  2. No, wrong, because elem.children[0] is the first child among elements. But there may be non-element nodes before it. So previousSibling may be a text node.

Please note that for both cases if there are no children, then there will be an error. For instance, if elem.lastChild is null, we can’t access elem.lastChild.nextSibling.