Skip to content

Instantly share code, notes, and snippets.

@davidhund
Created September 6, 2018 15:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidhund/f94fcfd2aa6835eef8de8dcfe949c638 to your computer and use it in GitHub Desktop.
Save davidhund/f94fcfd2aa6835eef8de8dcfe949c638 to your computer and use it in GitHub Desktop.
getSiblings in ES
/**
* 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