JS DOM - 01.02 - Navigating DOM

On top: ‘documnetElement’ and body

The topmost tree nodes are available directly as document properties:
<body> = document.body
<head> = document.head


Children: ‘childNodes’, ‘firstChild’, ’lastChild’

Child nodes are elements that are direct children. They are nested in the given one.
Descendants are all the elements that are nested in the given one, including their children and so on.
The childNodes collection lists all child nodes, including text nodes.

<script>
	for (let i=0; i < document.body.childNodes.length; i++) {
		alert( document.body.childNodes[i] );
		}  // Text, Div, Text, Ul, ... script

firstChild and lastChild give fast access to the first and last child.

elem.childNodes[0] === elem.firstChild
elem.childNodes[ elem.childNodes.length - 1] === elem.lastChild

DOM collections

childNodes looks like an array, but the collection is an array-like iterable object.
for..of can be used to iterate over them. But array methods wont work.

for (let node of document.body.childNodes) {
	alert(node);     // shows all nodes from collection
}

Array.from can be used create a real array from the collection if array methods are needed.

alert( Array.from(document.body.childNodes).filter );   // function

DOM collections are readable only, assignment doesn’t work.


Element-only navigation

Navigation properties listed above refer to all nodes. In childNodes we can see both text nodes, element nodes, and even comment nodes if they exist.
But for many tasks we don’t want text or comment nodes. We want to manipulate element nodes that represent tags and form the structure of the page.

  • children – only those children that are element nodes.
  • firstElementChildlastElementChild – first and last element children.
  • previousElementSiblingnextElementSibling – neighbor elements.
  • parentElement – parent element. (same as parentNode)

Replacing childNodes with children shows only elements.

<script>
	for (let elem of document.body.children) {
		alert( document.body.childNodes[i] );
		}  // Div, Ul, Div ... script
</script>

There are two main sets of them:

  • For all nodes: parentNodechildNodesfirstChildlastChildpreviousSiblingnextSibling.
  • For element nodes only: parentElementchildrenfirstElementChildlastElementChildpreviousElementSiblingnextElementSibling.

Some types of DOM elements, e.g. tables, provide additional properties and collections to access their content.