plainJS

Functions / Traversing

Get siblings of an element

jQuery $.siblings(), $.next(), $.nextAll(), $.prev, $.prevAll()

2015 page

This is the original page from 2015, kept at its address while the tested rewrite is in progress. The code is of its time: it ran in Internet Explorer and does not use what browsers have gained since. The rewrite replaces it here.

In short

Get the next, previous or all siblings of an element or retrieve siblings that match a given selector.

A helper function for fetching all siblings for a given DOM element –  or a filtered set of them:

js
function getSiblings(el, filter) {
    var siblings = [];
    el = el.parentNode.firstChild;
    do { if (!filter || filter(el)) siblings.push(el); } while (el = el.nextSibling);
    return siblings;
}

// example filter function
function exampleFilter(el) {
    return elem.nodeName.toLowerCase() == 'a';
}

// usage
el = document.querySelector('div');
// get all siblings of el
var sibs = getSiblings(el);
// get only anchor element siblings of el
var sibs_a = getSiblings(el, exampleFilter);

There are faster DOM methods for only getting the previous or next sibling of an element:

js
var previous = el.previousSibling;
var next = el.nextSibling;

Get all following siblings of an element, optionally filtered:

js
// this helper accepts a filter function as shown above: "exampleFilter()"
function getNextSiblings(el, filter) {
    var siblings = [];
    while (el= el.nextSibling) { if (!filter || filter(el)) siblings.push(el); }
    return siblings;
}

Get all preceding siblings of an element, optionally filtered:

js
// this helper accepts a filter function as shown above: "exampleFilter()"
function getPreviousSiblings(el, filter) {
    var siblings = [];
    while (el = el.previousSibling) { if (!filter || filter(el)) siblings.push(el); }
    return siblings;
}
Advertisement

Sources

  1. http://stackoverflow.com/questions/4378784/ (a 2015 source of the original page)