Contenido del Curso
HTML & JavaScript Interactivity for Beginners
HTML & JavaScript Interactivity for Beginners
DOM Traversal
Dom Traversal is the process of accessing one element from another element. There are several ways to traverse the DOM using different JavaScript methods. Let's get started, then with traversing downwards.
Traversing Downwards
Consider this code with a list of elements nested inside an <ul>
element.
index
index
index
Each <li>
element is called a child of the <ul>
element. So to access all the children of <ul>
elements, there are two methods:
querySeletor
orquerySelectorAll
;children
;
So let's use these two methods to access the child elements from the <ul>
element and display them in the 'demo'
paragraph element.
index
index
index
Traversing Upwards
Now we'll use the same code to explain how upward traversing works. The <ul>
element is the parent to each child <li>
element. To access the parent element of any <li>
element, first, you must select it using the querySelector method. Then call the parentElement
method to traverse to the parent <ul>
element. Finally, you can display it with the tagName
property. Let’s dive into it.
index
index
index
Another method you need to be familiar with when traversing the DOM upward is the closest
. Now, let's give an id to the second list element and add an anchor link as below:
index
index
index
Now we'll find the closest <ul>
element and change its style type to none, in other words, to remove its bullet points.
index
index
index
The key takeaway is that the closest
method traverses up the root from the specified element until it finds the element specified in the selector.
Traversing Sideways
There are three methods associated when traversing the DOM sideways:
nextElementSibling
;previousElementSibling
;- Combination of
parentElement
,children
, andindex
.
Let's have a look at each of them.
nextElementSibling
It gets the next immediate sibling after the current element. Now let's add anchor elements to all the elements.
index
index
index
Let's get to the first element and, from there, traverse to the next sibling.
index
index
index
previousElementSibling
Likewise, you can get the previous element using previousElementSibling
. We will use an index instead of class or id for a change in querySelector
.
index
index
index
Combination of parentElement, children, and index
Let's say you want to access the 4th element from the 1st element. Then from it, you go back to the parent using the parentElement
and then access the parent's children. Finally, using the index, you'll be able to locate the 4th element.
index
index
index
¡Gracias por tus comentarios!