Array of element's siblings

Angelos Chalaris · 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']

Recommended snippets

  • 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.