Traversing the DOM

Page section: posts
  • The item-list ul
  • item 2
  • item 3
  • item 4

Properties for DOM traversal

Property what it does
parentNode selects the parent of an element
childNodes select the children of an element inc. text which inc. white space, line breaks
children Produces an HTML collection of elements without text
firstChild Like childNodes this will select text, inc. white space and line breaks if there are any
firstElementChild Like children this will select elements, not text
lastChild equivalent to firstChild
lastElementChild equivalent to firstElementChild
nextSibling equivalent to firstChild
nextElementSibling equivalent to firstElementChild
previousSibling equivalent to firstChild
previousElementSibling equivalent to firstElementChild

With all of these plus querySelector and querySelectorAll you don’t need jQuery for DOM manipulation.

parentNode

gets the parent of the <ul> above.

Using parentNode you can select an elements parent.

itemList.parentNode.style.backgroundColor = '#1114';

Chaining .parentNodes

gets the parent of the parent of the <ul> above.

You can keep chaining these together.

An alternative is parentElement which works mostly the exact same way.

Differences between parentNode and parentElement

In most cases, it is the same as parentNode. The only difference comes when a node’s parentNode is not an element. If so, parentElement is null.

Since the element (document.documentElement) doesn’t have a parent that is an element, parentElement is null.

See MDN for more.

Child elements

These are accessed using childNodes or children.

to the console.

const wrapper = document.querySelector('#wrapper');
console.log(wrapper.childNodes);

The problem with childNodes is that they also select line breaks in the markup as text nodes. An alternative is children which works in much the same way without the text nodes. This produces an HTML collection instead of a node list.

to the console. Compare the outputs of both of these.

to the console selects the second child. to the console selects the second child.

HTML collections

Frequently when working with the DOM groups of elements, such as children aren’t stored as arrays but as HTML collections. These are array-like but have some differences. You cannot for instance use array methods like forEach on HTML collections. But you can iterate through the group instead using a for..of loop.

NB. Use for..of rather than for..in loops to iterate over collections. The for..in loops get all properties some of which won’t be needed.

These collections can also be made into arrays using Array.from().

turns a collection of the list items into an array then uses the forEach array method to iterate through and return the textContent of each item in an alert().

let itemCollection = itemList.children;

function it() {
    Array.from(itemCollection).forEach((item) => {
        alert(item.textContent);
    });
}

Table of Contents