Javascript 有没有办法检查两个 DOM 元素是否相等?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3649321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:35:22  来源:igfitidea点击:

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

javascriptdom

提问by Bob

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?

在Javascript中通过位置和元素的位置来查找元素是没有问题的。但是有没有通用的方法来比较它们?

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

我能想到的唯一方法是比较 id 或类名,但并非所有元素都有 id 或类名。

回答by Delan Azabani

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

回答by shabunc

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.

对于 IE,它的 DOM 元素具有非标准属性,uniqueID。但我无法想象它在这种情况下会有用,因为是的,您实际上可以比较两个指针。