JavaScriptDOM Manipulation

How to select sibling elements using JavaScript

Targeting HTML sibling elements for DOM manipulation

Introduction

For those of you who started developing on the front-end recently, you've probably heard time and time again that you should avoid using jQuery in new projects. While jQuery did solve very real problems, the margin between the benefits it provided and the advances made by JavaScript and the frameworks utilising it have significantly narrowed since its debut.

However, there are times when you still want to do basic DOM manipulation and using jQuery or any other framework/library in your stack would be overkill.

Then you have siblings... jQuery made targeting them especially easy with $.fn.siblings(). jQuery provided a convenient method to select the siblings of an element.

For example, given the following HTML:

<div>
  <span></span>
  <span></span>
  <a href="https://example.com"></a>
  <span></span>
  <span></span>
  <span></span>
</div>

Running the following code would produce a NodeList of 5 span elements.

$("div > a").siblings();

Of course, no native equivalent exists in Vanilla JS.

Using Array.prototype.filter

Since we don't want to modify objects we don't own, lets implement this as an anonymous function:

// 1. convert the node's parent's children into an array
// 2.1. filter that array
// 2.2. only include the children that are not the node
// 3. return the resulting array
const siblings = (node) => [...node.parentNode.children].filter(child => child !== node);

// test the "siblings" function
siblings(document.querySelector("div > a"));

Which should output an Array of 5 span elements:

[<span />, <span />, <span />, <span />, <span />];

Using Array.prototype.push

For those not using ES6+ or Babel, the following function is identical to the first:

function siblings(node) {
  // create a new array for the siblings
  var siblings = [];
  // get the node's parent's children
  var children = node.parentNode.children;
  // loop through the children
  for (var i = 0; i < children; i++) {
    // only add the child to the siblings list if it's not the current node
    if (child !== node) {
      siblings.push(child);
    }
  }
  // return the siblings
  return siblings;
}

// test the "siblings" function
siblings(document.querySelector("div > a"));

And should also output an Array of 5 span elements:

[<span />, <span />, <span />, <span />, <span />];

Closing thoughts

While jQuery may be on it's way to obsolescence, it is a paragon of JavaScript done right, it solved numerous problems across a project beloved by developers for making their lives easier. Its source code is a great resource for learning developers to see how to implement client side code and should be taken advantage of if you have the time.

Thank you for reading.