TIL some JS tree traversals
POSTED ON:
TAGS: dom jquery javascript
Ah, DOM tree traversal. It's the adventure that keeps on giving.
jQuery had some neat features with tree traversal.
https://api.jquery.com/category/traversing/tree-traversal/
<div id="parent">
<div id="element1">
<p></p>
<p></p>
<p></p>
</div>
<div id="element2"></div>
<div id="element3"></div>
</div>
<script>
$('#element').parent(); // gets #parent
$('#element').children(); // gets the 3 p elements
$('#element').siblings(); // gets #element2, and #element3
</script>
For the vanilla javascript way:
<div id="parent">
<div id="element1">
<p></p>
<p></p>
<p></p>
</div>
<div id="element2"></div>
<div id="element3"></div>
</div>
<script>
let element1 = document.querySelector('#element1');
let parent = element1.parentNode; // gets #parent
let children = element1.children; // gets the 3 p elements
let sibings = getAllSiblings(element1); // gets #element2, #element3
// No native features here
// So we havev to write a custom function
function getAllSiblings(element, parent) {
const children = [...parent.children];
return children.filter(child => child !== element);
}
</script>
Unfortunately, there is no native feature to get all siblings.
So what we can do is write a function that get the parent of the element, then gets all the children (and exclude the original).
Via https://stackoverflow.com/a/51670871/4096078
Related TILs
Tagged: dom