Array of element's siblings

JavaScript, Browser · Oct 19, 2020

Returns an array containing all the siblings of the given element.

  • Use Node.parentNode and Node.childNodes to get a NodeList of all the elements contained in the element's parent.
  • Use the spread operator (...) and Array.prototype.filter() to convert to an array and remove the given element from it.
const getSiblings = el =>
  [...el.parentNode.childNodes].filter(node => node !== el);
getSiblings(document.querySelector('head')); // ['body']

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub or Twitter.

More like this

  • Array to HTML list

    JavaScript, Browser

    Converts the given array elements into <li> tags and appends them to the list of the given id.

  • Create HTML element

    JavaScript, Browser

    Creates an element from a string (without appending it to the document). If the given string contains multiple elements, only the first one will be returned.

  • Render DOM element

    JavaScript, Browser

    Renders the given DOM tree in the specified DOM element.