0 votes
720 views
in Programming by

HI All, I want to discuss that why $(“body”) == $(“body”) returning false  also want to know the logic behind this, how can we see two different jQuery selectors point to same DOM object?

I hope you would help me thanks!

2 Answers

0 votes
by
Jquery selectors return arrays, don't they? when you compare arrays with == or === then you get false.
0
by
it looks like comparing a new instance of "body" to another new instance of "body".
like in java: "new Body() == new Body()";
0 votes
by
jQuery returns a new object each time it is called with a query selector. When you to == or ===, you are actually checking whether an object reference equals another object reference. In this case, it does not, since jQuery returns a new object each time. It would be the same as this: ({}) === ({}).

In your simple example, you can do this instead:

$('body').is('body')

However, depending on the real problem you have to solve, that may not be the answer. For example, if you need to check if two different selectors resolve to the exact same list of object (no more and no less), then this will not work.

You can do this to check if two selectors both found the one single DOM object:

$('.my-class').get(0) === $('.other-class').get(0)

This will check that the first element found is the same. You should, however, also check that the "length" property of each is 1, because it may not be.

This can get more and more complex, depending on what you actually need to solve.

Not a Member yet?

Ask to Folks Login

My Account

Your feedback is highly appreciated