How to check if two DOM elements are siblings?
<div>
<a></a>
<b></b>
<p></p>
</div>
<i></i>
Test if <b>
is a sibling of <a>
but not of <i>
var a = $('a'),
b = $('b'),
i = $('i');
a.siblings().is(b); // true (since "b" is sibling of "a")
a.siblings().is(i); // false (since "i" is sibling of "div" and not of "a")
a.siblings().is(a); // false (can't be singling of itself)
const elm_p = document.querySelector('p');
const elm_a = document.querySelector('a');
const elm_i = document.querySelector('i');
const areSiblings = (elm1, elm2) =>
elm1 != elm2 && elm1.parentNode == elm2.parentNode;
// tests
[
[elm_p, elm_a], // true
[elm_a, elm_p], // true
[elm_a, elm_a], // false
[elm_a, elm_i] // false
].forEach(([a,b]) => console.log(areSiblings(a,b)))
<div>
<a></a>
<b></b>
<p></p>
</div>
<i></i>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With