This solution provides a more detailed approach to creating a filter for selecting siblings.
There are three functions available to select only previous, only next, or all siblings. While there is room for improvement, this serves as a solid starting point if you require more specific control over the types of siblings you want to retrieve. It's a useful addition worth considering.
Check out the working example here
Get all next siblings
// This function will start from the current element and collect all the following 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;
}
Get all previous siblings
// This function will start from the current element and gather 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;
}
Get all siblings
// This function will start from the first child of the current element's parent and fetch 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;
}
Example filter to apply to the above functions
// This example filter only considers divs and spans but can be extended
function exampleFilter(elem) {
switch (elem.nodeName.toUpperCase()) {
case 'DIV':
return true;
case 'SPAN':
return true;
default:
return false;
}
}
HTML and testing output
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
var elem;
elem = document.getElementById('test2');
// With the filter applied, alerts 4
alert( getNextSiblings( elem, exampleFilter ).length );
// Without a filter, alerts 7
elem = document.getElementById('test2');
alert( getNextSiblings( elem ).length );
// Alerts 0
elem = document.getElementById('test2');
alert( getPreviousSiblings( elem, exampleFilter ).length );
// Alerts 5
elem = document.getElementById('test2');
alert( getAllSiblings( elem, exampleFilter ).length );