JSFiddle - React, Tailwind, and code Playground

by Michael Russell

HTML

<div id='test'>
    <div id='test2'>asdf</div>
    <br /> sdf
    <div>asdfasdf<span>asdf</span></div>
    <div>a</div>
    <span>a</span>
    <br />
    <div>d</div>
    <hr/>
</div>

JavaScript

//this will start from the current element and get all of the next siblings

function getNextSiblings(elem, filter) {
    var sibs = [];
    while (elem = elem.nextSibling) {
    		if (elem.nodeType === 3) continue; // text node
        if (!filter || filter(elem)) sibs.push(elem);
    }
    return sibs;
}

//this will start from the current element and get all the previous siblings

function getPreviousSiblings(elem, filter) {
    var sibs = [];
    while (elem = elem.previousSibling) {
    		if (elem.nodeType === 3) continue; // text node
        if (!filter || filter(elem)) sibs.push(elem);
    }
    return sibs;
}

//this will start from the first child of the current element's parent and get all the siblings

function getAllSiblings(elem, filter) {
    var sibs = [];
    elem = elem.parentNode.firstChild;
    do {
    		if (elem.nodeType === 3) continue; // text node
        if (!filter || filter(elem)) sibs.push(elem);
    } while (elem = elem.nextSibling)
    return sibs;
}

// only counts divs and spans but could be made more complex

function exampleFilter(elem) {
    switch (elem.nodeName.toUpperCase()) {
    case 'DIV':
        return true;
    case 'SPAN':
        return true;
    default:
        return false;
    }
}
var elem;
elem = document.getElementById('test2');

//with filter alerts 4
alert(getNextSiblings(elem, exampleFilter).length);

elem = document.getElementById('test2'); // put elem back to what it was
// no filter, alerts 7
alert(getNextSiblings(elem).length);

elem = document.getElementById('test2'); // put elem back to what it was
// alerts 0
alert(getPreviousSiblings(elem, exampleFilter).length);
elem = document.getElementById('test2'); // put elem back to what it was
// alerts 5
alert(getAllSiblings(elem, exampleFilter).length);