Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if elements (DOM Nodes) are siblings

How to check if two DOM elements are siblings?

Example DOM structure:

<div>
    <a></a>
    <b></b>
    <p></p>
</div>
<i></i>

Test if <b> is a sibling of <a> but not of <i>

like image 280
vsync Avatar asked Dec 10 '22 16:12

vsync


1 Answers

jQuery:

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)

Vanilla:

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>
like image 131
vsync Avatar answered Dec 21 '22 00:12

vsync