Get all siblings of an element
Return the other element children of the element’s parent.
function siblings(element) { return element.parentElement ? [...element.parentElement.children].filter(child => child !== element) : []; }
Usage
Markup
<ul><li id="a">A</li><li id="b">B</li><li id="c">C</li></ul>
Script
siblings(document.querySelector('#b')).map(element => element.id); // → ['a', 'c']
siblings(document.createElement('li')); // → []
Know the limits
- Element siblings only: text and comment nodes are skipped. The original threw a TypeError for an element without a parent; this version returns [].
The function above is the code the usage lines run. It does not validate its arguments; add checks where it receives untrusted input.
Source & maintenance
Based on Get all siblings of an element from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Returns [] for an element without a parent instead of throwing. Executed in Chromium. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Check if a given DOMRect is contained within another DOMRect — True when the target lies inside the container or on its edges.
- Check if two DOMRects intersect — Two rects intersect when they meet on both axes.
- Compare two DOMRects for size and position match — Compare x, y, width and height exactly.