How to traverse the dom in Javascript

3 min readFeb 16, 2021

When we started learning to code, flatiron started us with Ruby because it was an “easier” language. I don’t agree with this because there are limitations with Ruby, Javascript has so many different ways to do the same thing. This allows you to make your own structure which is always more inspiring. There are three ways to traverse the dom, you can go downwards, upwards, and sideways.

The functions you can use to access the dom downwards is .querySelector or .querySelectorAll. This starts from the top and checks to see the first element in the html that matches your selector. You can use .querySelectorAll to find all of the elements that match your selector. If you are looking for a class then you use . and when you are looking for an id it is a #.

You can also use .children to access the child elements from your query selector, this is a great for when you have to access multiple items in a specific class. You can also use the index to find a specific element in the list you want to manipulate and can save it to a variable.

The next way to access is upwards, the functions you use to do this are parent element and closest. You can use a query selector to access the first element that matches your selector and then use parent Element to find the class that matches. This is great for when you are working with a large html and you are not sure where to start.

Parent element is a great way to find an element when it is one level up but if you want to find an element that is a couple levels further you can use closest. This is a great example of being able to do something so many different ways with javascript, being able to traverse the dom is a crucial part of javacript.

The third way to traverse the dom is sideways, you can use nextElementSibling or previousElementSibling. This nextElementSibling function allows you select the next element in the class and previousElementSibling allows you to access the previous element.

--

--

No responses yet