Sometimes, we want to loop through all descendants of a div with JavaScript.
In this article, we’ll look at how to loop through all descendants of a div with JavaScript.
How to loop through all descendants of a div with JavaScript?
To loop through all descendants of a div with JavaScript, we can select all the descendants with getElementsByTagName
.
For instance, we write:
<div id='id'>
<p>
bar
</p>
<p>
baz
</p>
<p>
foo
</p>
</div>
to add a div with some descendant elements.
Then we select the descendants and loop through them with:
const ancestor = document.getElementById('id')
const descendents = ancestor.getElementsByTagName('*');
for (const d of descendents) {
console.log(d)
}
We select the div with ID id
with getElementById
.
Then we call ancestor.getElementsByTagName
with '*'
to select all the descendant elemnts from ancestor
.
Finally, we loop through them with a for-of loop.
Therefore, we should see all the p elements logged.
Conclusion
To loop through all descendants of a div with JavaScript, we can select all the descendants with getElementsByTagName
.