Last active
August 29, 2021 15:56
-
-
Save cferdinandi/6203237 to your computer and use it in GitHub Desktop.
A simple script to get all siblings of an element.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} |
Neat! :)
Line 11 should read:
if ( sibling.nodeType == 1 && sibling != skipMe )
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
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
Thank you! Used in www.achrafkassioui.com/birdview/