Created
September 6, 2018 15:44
-
-
Save davidhund/f94fcfd2aa6835eef8de8dcfe949c638 to your computer and use it in GitHub Desktop.
getSiblings in ES
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
/** | |
* getSiblings(element) | |
* | |
* @param {HTMLElement} HTML Element to find siblings of | |
* @returns {Array} HTML sibling elements of `element` | |
* | |
* Based on: https://twitter.com/ChrisFerdinandi/status/1037350582887927809 | |
*/ | |
const getSiblings = (elem) => { | |
// Return empty Array when given Element is not given or not a HTML Element | |
if(!elem || elem.nodeType !== 1) return []; | |
// [1] Get parentNode of Element | |
const parent = elem.parentNode; | |
// [2] Get all children of parentNode | |
const childs = parent.children; | |
// [3] Return array of children (converted nodeSet - using spread) but filter out Element | |
return [...childs].filter(child => child !== elem ); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment