With the constant influx of new JavaScript frameworks literally every year, we web developers eventually end up with a thousand different ways to perform the same set of tasks. But we shan't be discussing those JavaScript frameworks today, the focus of this article is to explain what a DOM is and how to traverse it using pure vanilla JavaScript.
Prerequisites
To get the best out of this tutorial it is strongly advised that you have:
A fair understanding of HTML
At least some basic understanding of CSS
DOM QUERIES
Before attempting to understand what DOM queries are and how they work, it is important to have an idea of what DOM means.
DOM is an abbreviation for "Document Object Model", to keep it simple, it's just the JavaScript term for an HTML file. When developers say DOM they're referring to the HTML file that their JavaScript code is working with and traversing the DOM means navigating your way from one HTML element to another using JavaScript.
DOM queries are the numerous JavaScript syntaxes used to select HTML elements, without further ado, let's check them out.
document.getElementById()
This is by far the most popular DOM query, it is the most fundamental way to select an HTML element.
// the element's id goes in the parenthesis, it must be in quotes
document.getElementById('id')
What the above example does is that it goes through the HTML code your script is working with really fast and it returns the first element it comes across that has the id you specified in the parenthesis. PS: It is considered bad practice to have different elements with the same id in your HTML code, as it can get confusing and lead to mistakes.
querySelector()
This is another query used to select an element, this query takes a CSS selector as a parameter, code example...
// This query returns an h1 element that has a class name of 'head'
document.querySelector('h1.head')
What if I want to select multiple elements at once?
Doing this is just as easy as selecting a single element, in fact, I believe the biggest difference is in the syntax, here are the DOM queries used to select multiple elements at the same time:
document.getElementsByClassName()
document.querySelector()
document.getElementsByTagName()
// This query returns an array of all elements with the class name "cat"
document.getElementsByClassName('cat')
// This query returns an array of all <li> elements that have a class name of "cold"
document.querySelectorAll('li.cold')
// This query returns an array of all <p> elements in your HTML code
document.getElementsByTagName('p')
As developers sometimes we need to single out one element from an array of returned elements and give it a slightly different instruction from its siblings, that can be done by specifying the order in which the element we want to single out appears in the array, it is very important to note that the numbering starts from 0, not 1, code example...
// This query will return only the first element that has a class name of "cat" in your HTML code
document.getElementsByClassName('cat')[0]
//This query will return only the second <p> element in your HTML code
document.getElementsByTagName('p')[1]
// This query will return only the third <li> element that has a class name of "cold" in your HTML code
document.querySelectorAll('li.cold')[2]
Caching the selected element in a variable
Instead of having to type "document.getElem..." every time you need to select a particular element that you're repeatedly working with, you can select it once, store it in a variable and just refer to that variable whenever you need to work with the element, this comes in very handy when you need to modify the same element multiple times in your script. Here's how it works...
// I select an element with an id of '1stpara' and store it in a variable called firstParagraph
var firstParagraph = document.getElementById('1stPara')
// Then using the declared variable name, I write some text into the element
firstParagraph.textContent = "Hey there, I'm Eniitan"
Here I simply stored the element in a variable called firstParagraph, then I wrote some content into it, I can work on that same element by using the declared variable name throughout the script as many times as I want.
DOM queries that return an array of elements can also be stored in a variable (even when used to single out an element from the array), code example...
// This stores all <li> elements in a variable called elarray
var elarray = documents.getElementsByTagName('li')
// This stores only the first among all the <li> elements in a variable called firstLi
var firstLi = elarray[0]
// A singled out element can also be stored directly like this
var thirdCold = document.querySelectorAll('li.cold')[2];
DOM queries are the most basic ways to select HTML elements, as a matter of fact, if you started learning JavaScript today DOM queries would be the first area to look into, and that's why I've introduced them first, seeing as you're currently learning JavaScript from my article.
TRAVERSING THE DOM
Now, it is time to dive into the primary focus of this article. Traversing the DOM means navigating your way from a selected element to other elements near it without having to write new DOM queries. JavaScript provides us with various properties that get this job done and they are split into 3 major areas, or shall we say 3 different branches of the same family.
Parents
Children
Siblings
Parents
This is how an HTML script is structured.
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>Your Heading</h1>
<p>Whatever is in your first paragraph</p>
</body>
</html>
In this example <head>
is the parent of <title>
, and <body>
is the parent of both <h1>
and <p>
. So let's say you select an element in your JavaScript code and store it in a variable like this...
var heading = document.getElementsByTagName('h1')[0]
If you wish to make some changes to the parent of the element you have just selected, instead of having to write another DOM query to select its parent, the element becomes your root element and you can simply navigate to its parent from it, this is how...
heading.parentNode
now I have just selected the parent of our root element which we stored in the 'heading' variable earlier, if I want to make any modification to that parent, the syntax would depend on the kind of modification I want to make, but this is an example...
// This adds a paragraph to the body of the HTMl file
heading.parentNode.insertAfter('<p>Vox populi vox dei</p>')
That's it for the parentNode, now let's talk about the children.
Children
A child element is an element that is directly inside another element, code example...
<p>
<ul>
<li>peaches</li>
<li>lemonade</li>
<li>avocado</li>
</ul>
</p>
In this example, the <ul>
element is the child of the <p>
element and the 3 <li>
elements are all children of the <ul>
element. There are different JavaScript properties for selecting child elements, the right one to use depends on the situation, are you trying to select a particular child element? or all the children of the root element?
.firstElementChild
This property returns only the first child of the root element.
// This selects the <ul> element from the example above var list = document.getElementsByTagName('ul')[0] // This changes the content of the first child of the <ul> element list.firstElementChild.textContent = 'Ramen'
.lastElementChild
This property returns only the last child of the root element.
// This changes the content of the last child of the <ul> element list.lastElementChild.textContent = 'Croissant'
.children
This property returns all the children of the root element, any modification made using the ".children" property will affect all the children of the root element.
// This loops through the whole list and changes each text content to Diet Coke for (let element of list.children){ element.textContent = 'Diet Coke' }
Siblings
Siblings are elements that are side by side with the root element, they are neither outside (parent) nor inside (child) of the root element, they are on the same level as the root element. Code example...
<p>
<ul>
<li>peaches</li>
<li>lemonade</li>
<li>avocado</li>
</ul>
</p>
in this example, the 3 <li> elements are siblings of each other. When it comes to traversing the DOM on the sibling level there are two different properties, the right choice depends on the position of the sibling you're trying to select in relation to the position of the root element, does it come before the root element? or does it come after?
.previousElementSibling
This returns the element that comes just before the root element.
// This selects the 2nd <li> element from the example above var midListItem = document.getElementsByTagName9('li')[1] // This returns the 1st <li> element from the example above midListItem.previousElementSibling
.nextElementSibling
This returns the element that comes immediately after the root element.
// This returns the 3rd <li> element from the example above midListItem.nextElementSibling
CONCLUSION
Now that you've learned how to select elements and how to traverse the DOM from the root element, what's left for you to do is to get on your computer and put in some practice, the best way to learn is by doing.
That's it for this article guys, thank you for reading this far, a follow would be greatly appreciated ๐, catch you on the next one โ๏ธ.