Why does $(“body”) == $(“body”) return false?

后端 未结 3 490
礼貌的吻别
礼貌的吻别 2020-12-15 15:39

How come the equation in the title is false? How do check if two jQuery selectors point to the same DOM object?

相关标签:
3条回答
  • 2020-12-15 16:29

    You are comparing two distinct jQuery objects because you call $() twice (once for each side of the equation), and as MooGoo explains jQuery creates new wrapper objects for each time you call it. That's why the comparison ends up returning false.

    You can extract a DOM object from each jQuery object by either using get() or array dereferencing, then compare these elements. The following both return true because both identical selectors match the same body DOM element:

    $('body').get(0) == $('body').get(0)
    $('body')[0] == $('body')[0]
    

    If you want to test against a jQuery selector, use is(). Note that, unless your selectors are identical, the selectors you use may not necessarily match the same DOM elements (it's still better to use the above). This also returns true:

    $('body').is('body')
    
    0 讨论(0)
  • 2020-12-15 16:39

    Use $.is()

    http://api.jquery.com/is/

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

    Unlike other filtering methods, .is() does not create a new jQuery object. Instead, it allows you to test the contents of a jQuery object without modification. This is often useful inside callbacks, such as event handlers...

    0 讨论(0)
  • 2020-12-15 16:40

    Because jQuery creates a new wrapper object for each $ call, and in Javascript all objects are distinct, even if they have the exact same properties/methods.

    On the other hand, document.body == document.body would evaluate to true.

    0 讨论(0)
提交回复
热议问题