Hey there! any question in your mind? Ask It Now!.

Popular Categories

Reason behind why body returns false?

0 votes
asked in Programming by Priya

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
answered by Alex
Jquery selectors return arrays, don't they? when you compare arrays with == or === then you get false.
commented by anonymous
it looks like comparing a new instance of "body" to another new instance of "body".
like in java: "new Body() == new Body()";
0 votes
answered by Kiril Vatev
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:


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.

Related Questions

+4 votes
5 answers 3,572 views
+1 vote
1 answer 1,017 views
+1 vote
1 answer 860 views
+1 vote
2 answers 133 views
+2 votes
1 answer 349 views
+3 votes
1 answer 4,027 views
+1 vote
1 answer 169 views
asked in Programming by amit_pammu Expert (5,030 points)
+1 vote
1 answer 182 views
+1 vote
1 answer 278 views

Not a Member yet?

Ask to Folks Login

My Account
357 Folks are online
0 members and 357 guest online
Your feedback is highly appreciated