How To Traverse The DOM In JavaScript
Intro
One of the most important skills of a web developer is DOM traversal and being able to select HTML elements with JavaScript. This will be a guide on my top 10 of the must know methods and hopefully this will help you master DOM traversal by the end of the guide.
Fair warning!
This is a guide for developers with at least some basic knowledge in HTML & JavaScript
DOM Nodes
Before we dive into the traversal methods, let’s look at the brief explanation of the DOM and Node Relationships from W3school.
According to the W3C HTML DOM standard, everything in an HTML document is a node:
- The entire document is a document node
- Every HTML element is an element node
- The text inside HTML elements are text nodes
- All comments are comment nodes
Node Relationships
The nodes in the node tree have a hierarchical relationship to each other. The terms parent, child, and sibling are used to describe the relationships.
- In a node tree, the top node is called the root (or root node)
- Every node has exactly one parent, except the root (which has no parent)
- A node can have a number of children
- Siblings (brothers or sisters) are nodes with the same parent
Navigating Between Nodes
Here’s a chart I drew up showing the following node properties to navigate between nodes
- parentNode
- previousSibling
- nextSibling
- firstChild
- lastChild
- childNodes[nodeNumber]
Traversal Methods
Before we get into the methods, below is a HTML node tree I drew up with a div representing a grandparent node which has two parent divs and finally each parent div has two children nodes each
- parent-1, parent-2 belongs to grandparent
- child-1, child-2 belongs to parent-1
- child-3, child-4 belongs to parent-2
- getElementById - This one is a classic, find a single element node by targeting the id
2. getElementsByClassName - This is our second classic way to select multiple elements at once, let’s say to target both our parent divs
3. querySelector - This is my favorite by far, a lot easier to use a single method to target classes or ids
4. querySelectorAll - similar to querySelector but used to select multiple element nodes
5. parentElement - used to target one level up the DOM tree to target the parent node
6. previousElementSibling - used to target one node to the left in terms of DOM tree
7. nextElementSibling - used to target one node to the right in terms of DOM tree
8. firstElementChild - used to target the first node down the DOM tree
9. lastElementChild - used to target the last node down the DOM tree
10. childNodes[node #] - last on my list but another one of my favorites, the childNodes method takes in a number to target child nodes of a parent
That’s it! Thank you for checking out my DOM traversal guide. I hope this has helped you get a better understanding in traversing up and down the DOM tree and stay tuned for more coding guides.