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

JavascriptDom

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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) ...

Solution 3 - Javascript

=== Operator still relevant https://developer.mozilla.org/en-US/docs/Web/API/Node/isSameNode

Even if you make changes to the DOM, === operator works fine.

const body = document.body; body.setAttribute("test","done"); const _body = document.body; body === _body // true.

:).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBobView Question on Stackoverflow
Solution 1 - JavascriptshabuncView Answer on Stackoverflow
Solution 2 - JavascriptDelan AzabaniView Answer on Stackoverflow
Solution 3 - JavascriptFATCHOLAView Answer on Stackoverflow