Explain Codes LogoExplain Codes Logo

Is there a way to select sibling nodes?

javascript
dom-manipulation
javascript-apis
sibling-nodes
Anton ShumikhinbyAnton Shumikhin·Dec 6, 2024
TLDR

Quickly select sibling nodes using CSS combinators: + for the directly adjacent sibling and ~ for all following siblings. For immediate siblings:

h1 + p { color: blue; } /* Blue P is the new Black */

And for every sequential paragraph:

h1 ~ p { color: green; } /* Code, code's green buddy, field is green */

These selectors target siblings that share the same parent, ideal for specific sibling relationships within an HTML structure.

Access and manipulate siblings using JavaScript

Despite CSS selectors' power, we sometimes need JavaScript for dynamic manipulation beyond static styling.

Direct sibling access with DOM methods

DOM methods come in handy for accessing siblings via JavaScript. The node.nextElementSibling targets the next sibling:

const nextSibling = element.nextElementSibling; // Found the next contestant

And node.previousElementSibling fetches the previous sibling:

const previousSibling = element.previousElementSibling; // Turn back, turn back!

These methods are ignorant of text nodes, allowing you to deal with element nodes. No more ghost text nodes spawned by whitespace using nextSibling and previousSibling.

Custom sibling functions for tailored manoeuvres

Sometimes, we need more control for accessing siblings based on complex logic. Here's a custom function getSiblings(element) which returns an array of all siblings,

function getSiblings(element){ let siblings = []; [...element.parentNode.children].forEach(sibling => { if(sibling !== element) siblings.push(sibling); }); return siblings; } // Now we are playing sibling Tetris!

Enter jQuery

If you're using jQuery, the .siblings() method can be a breeze:

$('#innerId').siblings().hide(); // Because hide and seek is still fun

However, native DOM API provide similar functionality, without jQuery carrying you on its shoulders.

Text and comment nodes? Not on my watch!

Be careful with text and comment nodes when using previousSibling. Stick to previousElementSibling and nextElementSibling to target only the meaningful element nodes and not noisy text nodes.

Handling dynamically loaded content

When the HTML content isn't static, effectively and safely managing siblings is paramount.

Safe operations on the invisible nodes

In the world of dynamic HTML, safety is king. Ensure operations affecting siblings don't cause unintended manipulation of nodes not visible at runtime. Remember to cache nodes before loops or repetition to minimize costly repaints and reflows.

Advanced sibling selection and manipulation

For complex needs, such as finding siblings based on stringent criteria or manipulating siblings in bulk, JavaScript's array methods and DOM manipulation techniques can come to the rescue. Equip yourself well for the sibling battleground!