jQuery compare two DOM object?

倖福魔咒の 提交于 2019-11-28 09:59:25

You can use the jQuery.is function:

Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.

if (selected_object.is(current_object)) {
   ...    
}

An alternate solution is to use jQuery.get function to get the raw elements and compare them using == or === operator:

if (selected_object.get(0) == current_object.get(0)) {
   ...
}

jsFiddle demo

There's good answer provided... but it's important to understand, why you directly can't compare selectors in jQuery.

jQuery selectors return data structures which will never be equal in the sense of reference equality. So the only way to figure this out is to get DOM reference from the jQuery object and to compare DOM elements.

The simplest comparison of DOM reference for the above example would be:

selected_object.[0] == current_object.[0]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!