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']

More like this

  • JavaScript DOM Querying

    Learn how to query the DOM quickly and efficiently with this collection of JavaScript tips and tricks.

    Collection · 15 snippets

  • Array to HTML list

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

    JavaScript, Browser · Oct 20, 2020

  • Vertical offset of element

    Finds the distance from a given element to the top of the document.

    JavaScript, Browser · Jan 5, 2021

  • Render DOM element

    Renders the given DOM tree in the specified DOM element.

    JavaScript, Browser · Oct 13, 2021