Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to check if two DOM elements are equal?

Tags:

javascript

dom

It's no problem to find an element by position and the position of an element in Javascript. But is there are general way to compare them?

The only way I could think of is comparing ids or classnames, but not all elements have ids or classnames.

like image 634
Bob Avatar asked Sep 06 '10 05:09

Bob


People also ask

What is the name of the method to check equality of two nodes?

The isEqualNode() method of the Node interface tests whether two nodes are equal. Two nodes are equal when they have the same type, defining characteristics (for elements, this would be their ID, number of children, and so forth), its attributes match, and so on.

How do you check for equality of two nodes in node JS?

isSameNode() The isSameNode() method of the Node interface is a legacy alias the for the === strict equality operator. That is, it tests whether two nodes are the same (in other words, whether they reference the same object).

How do I identify a DOM element?

The easiest way to find an HTML element in the DOM, is by using the element id.


2 Answers

In modern browsers there are two methods for comparing nodes.

var a = document.createElement('div'); var b = document.createElement('div'); b.isEqualNode(a); // true 

but

b.isSameNode(a); //false 

And as for IE, it's DOM elements have non-stanard attribute, uniqueID. But I can't imagine it can be useful in this case, since yes, you actually can compare two pointers.

like image 171
shabunc Avatar answered Sep 22 '22 08:09

shabunc


If you want to compare two element pointers for being the same element, just use the comparison operator. This can be easily proven because

document.body === document.body 

For example, if I somehow had references to two elements I didn't know:

if (element1 === element2) ... 
like image 28
Delan Azabani Avatar answered Sep 19 '22 08:09

Delan Azabani