Traversing the DOM

This YouTube video was created by Steve Griffith.

While it is always easier to select an element directly using getElementById() or querySelector(), there are times when that will be difficult to do. During those times it might be necessary to move through the DOM from a specific point. Fortunately, JavaScript provide many different methods for doing just that.

children

The childrenopen in new window property is a read-only property that contains all of the child elements of a specific element.

const $list = document.getElementById('list')
const $items = list.children // HTMLCollection

NOTE

An HTMLCollectionopen in new window is an array-like object of HTML elements that offers methods and properties for access and manipulating the elements.

firstElementChild

The firstElementChildopen in new window property returns an element's first child element, or null if the element has no children.

const $list = document.getElementById('list')
const $firstItem = list.firstElementChild // HTML Element

NOTE

There is also a [lastElementChild] property, which returns an element's last child element.

nextElementSibling

The nextElementSiblingopen in new window is a property that returns an element's next sibling element.

const $list = document.getElementById('list')
const $firstItem = list.firstElementChild // HTML Element
const $nextItem = firstItem.nextElementSibling // HTML Element

NOTE

There is also a `previousElementSiblingopen in new window is a property that returns an element's previous sibling element.