omega
omega

Reputation: 43883

How to check if two DOM nodes are siblings without jquery?

How can you check if two DOM nodes are siblings without jquery?

<div>
   <a></a>
   <b></b>
   <c>
       <d></d>
   </c>
</div>

a and c are siblings but a and d are not. a and a are not siblings.

Upvotes: 1

Views: 456

Answers (3)

Nick Grealy
Nick Grealy

Reputation: 25912

Just use .parentElement or .parentNode to determine if they share the same parent.

var a = document.querySelector('a');
var b = document.querySelector('b');
var c = document.querySelector('c');
var d = document.querySelector('d');


function areSiblings(x, y) {
  return x !== y && x.parentElement === y.parentElement;
}

function areSiblings2(x, y) {
  return x !== y && x.parentNode === y.parentNode;
}

console.log(areSiblings(a, b)); // true
console.log(areSiblings(a, c)); // true
console.log(areSiblings(a, d)); // false

console.log(areSiblings2(a, b)); // true
console.log(areSiblings2(a, c)); // true
console.log(areSiblings2(a, d)); // false
<div>
   <a></a>
   <b></b>
   <c>
       <d></d>
   </c>
</div>

Upvotes: 1

Vivek Athalye
Vivek Athalye

Reputation: 2979

Why not check parentNode (or parentElement) property?

function areSiblings(a, b) {
  return a!=b && a.parentNode == b.parentNode; 
}

Upvotes: 2

Daniel A. White
Daniel A. White

Reputation: 190956

Just check their .parentElement property.

let isSibling = el1 !== el2 && el1.parentElement === el2.parentElement;

Upvotes: 5

Related Questions