Understanding the DOM is essential in your web development career. I need to know how to select different elements in the DOM. You can then read or modify their contents.
DOM traversal describes how to navigate the tree-like structure that an HTML document produces. Here’s a complete guide on how to traverse the DOM using JavaScript.
What is DOM traversal?
The Document Object Model, or DOM for short, is a tree-like representation of an HTML document. It provides an API that allows web developers to interact with her website using JavaScript.
All items in the DOM are called nodes. You can manipulate the structure, content, and style of HTML documents only through the DOM.
DOM traversal (also known as walking or navigating the DOM) is the act of selecting nodes in the DOM tree from other nodes. You’re probably already familiar with some of the ways to access elements in the DOM tree by ID, class, or tag name.You can use a method like document. querySelector() and document. getElementById() to do so.
There are other methods that can be used in combination to navigate the DOM in a more efficient and robust way. As you can imagine, searching from a known point on the map is better than doing a full search.
For example, selecting a child element from a parent element is easier and more efficient than searching through the tree.
Sample document to traverse
Once you have access to a particular node in the DOM tree, you can access related nodes in various ways. You can move down, up, or sideways in the DOM tree from the selected node.
The first method searches for elements starting at the top node (such as the document node) and working downwards.
The second method is the opposite. Search the outer element by traversing up the tree from the inner element. The last way is if you want to find an element from another element at the same level (meaning the two elements are siblings) in the document tree.
As an example, consider the following example HTML document:
<!DOCTYPE html>
<html lang="en"><head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Sample page</title>
</head>
<body>
<main>
<h1>My Page Title</h1>
<p>Nice caption goes here</p>
<article class="first__article">
<h2>List of amazing fruits</h2>
<p>Must eat fruits</p>
<div class="wrapper-1">
<ul class="apple-list">
<li class="apple">Apples</li>
<li class="orange">Oranges</li>
<li class="avocado">Avocados</li>
<li class="grape">
Grapes
<ul>
<li class="type-1">Moon drops</li>
<li>Sultana</li>
<li>Concord</li>
<li>Crimson Seedless</li>
</ul>
</li>
<li class="banana">Bananas</li>
</ul>
<button class="btn-1">Read full list</button>
</div>
</article>
<article class="second__article">
<h2>Amazing places in Kenya</h2>
<p>Must visit places in Kenya</p>
<div class="wrapper-2">
<ul class="places-list">
<li>Maasai Mara</li>
<li>Diani Beach</li>
<li>Watamu Beach</li>
<li>Amboseli national park</li>
<li>Lake Nakuru</li>
</ul>
<button class="btn-2">Read full list</button>
</div>
</article>
</main>
</body>
</html>
Traverse the DOM downwards
You can traverse downwards through the DOM using one of two methods. The first is the general selector method (element. querySelector again element. querySelectorAll).Second, you child again child node property. Besides, he has two special properties. last child and first child.
Using selector methods
You can use the querySelector() method to find one or more elements that match a given selector. For example, you can use the following to find the first element with a class of “first-article”: document.querySelector(‘.first-article’). and to get all h2 Elements in the document include querySelectorAll Method: document.querySelectorAll(‘h2’). of querySelectorAll The method returns a node list of matching elements. You can select each item using bracket notation.
const headings = document.querySelectorAll('h2');
const firstHeading = headings[0];
const secondHeading = headings[1];
The main caveat when using selector methods is that you should use the appropriate symbol where applicable before the selector, just like you do in CSS. For example, class is “.classname” and ID is “#id”.
Note that the result will be an HTML element, not just the inner content of the selected element.To access the content, the node’s Inner HTML property:
document.querySelector('.orange').innerHTML
Using the children or childNodes property
of child The property selects all immediate child elements of a particular element.Here is an example child Actual properties:
const appleList = document.querySelector('.apple-list');
const apples = appleList.children;
console.log(apples);
logging apple Display in the console the set of all list items directly under the element with the “apple-list” class as an HTML collection. HTML collections are array-like objects, so you can select items using bracket notation, similar to querySelectorAll.
Unlike child property, child node Returns all direct child nodes, not just child elements. If you are only interested in child elements, e.g. list items only, child property.
Using special lastChild and firstChild properties
These two methods are not as robust as the first two methods. As their name suggests, last child and first child The property returns the last and first child nodes of the element.
const appleList = document.querySelector('.apple-list');
const firstChild = appleList.firstChild;
const lastChild = appleList.lastChild;
Traverse up the DOM
can be used to move up the DOM. parent element (again parent node) and the nearest properties.
Using parentElement or parentNode
both parent element again parent node The property allows you to select the parent node of the selected element up one level. The crucial difference is parent element Selects only parent nodes that are elements. on the other hand, parent node You can select the parent whether it is an element or another node type.
In the code sample below, parent element To select the div with class “wrapper-1” from “apple-list”:
const appleList = document.querySelector('.apple-list');
const parentDiv = appleList.parentElement;
console.log(parentDiv);
Using closest properties
of the nearest The property selects the first parent element that matches the specified selector. You can select multiple levels instead of just one. For example, if you already have a button with class “btn-1” selected, major elements that use the nearest Properties are:
const btn1 = document.querySelector('.btn-1');
const mainEl = btn1.closest('main');
console.log(mainEl);
like query selector and querySelectorAllUse the appropriate selector in the . the nearest Method.
Traverse the DOM horizontally
There are two ways to move horizontally through the DOM.can be used nextElement Siblings again previous element sibling. use nextElement Siblings select the next sibling element, previous element sibling Select the previous sibling.
const orange = document.querySelector('.orange');
const apple = orange.previousElementSibling;
const avocado = orange.nextElementSibling;
There is also an equivalent next brother and ex brother Properties to select from all node types, not just elements.
Chain DOM traversal properties and methods to do more
All the above methods and properties allow you to select any node in the DOM. However, in some cases it’s better to move up first and then down or sideways. In that case, chaining different properties can be useful.