Today I Learned - Rocky Kev

TIL some JS tree traversals

POSTED ON:

TAGS:

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:

TIL Dirty bit systems in browsers

In order not to do a full layout for every small change, browsers use a 'dirty bit' system. A renderer that is changed or added marks itself and its children as 'dirty': needing layout. There are two flags: 'dirty', and 'children are dirty' which means that although the renderer itself may be OK, it has at least one child that needs a layout.

TIL prepend

When you're creating new elements in Javascript, you want to attach the new element to something that exists in the DOM already. You do that with append, and prepend.

TIL some JS tree traversals

Ah, DOM tree traversal. It's the adventure that keeps on giving.