Skip to content

Instantly share code, notes, and snippets.

@cferdinandi
Last active August 29, 2021 15:56
Show Gist options
  • Save cferdinandi/6203237 to your computer and use it in GitHub Desktop.
Save cferdinandi/6203237 to your computer and use it in GitHub Desktop.
A simple script to get all siblings of an element.
/**
* Get siblings of an element
* @param {Element} elem
* @return {Object}
*/
var getSiblings = function (elem) {
var siblings = [];
var sibling = elem.parentNode.firstChild;
var skipMe = elem;
for ( ; sibling; sibling = sibling.nextSibling )
if ( sibling.nodeType == 1 && sibling != elem )
siblings.push( sibling );
return siblings;
}
@AchrafKassioui
Copy link

@mihaiconstantin
Copy link

Neat! :)

@bjfresh
Copy link

bjfresh commented Jun 14, 2018

Line 11 should read:
if ( sibling.nodeType == 1 && sibling != skipMe )

@yairEO
Copy link

yairEO commented Oct 22, 2020

Just came here randomly. saw the code, decided to attempt a better solution:

var getSiblings = elm => elm && elm.parentNode && [...elm.parentNode.children].filter(node => node != elm)

children gives only elements, filter only selects those other than the target reference node, and [...] converts the HTMLCollection into a "real" array, for the filter to be able to work.

I've wrote an extensive answer here

@cferdinandi
Copy link
Author

Shorter, sure. Better? Subjective.

I should update this to use filter(). But arrow functions and spread operators are going to severely limit browsers that can use your approach.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment