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

Popular Categories





Reason behind why body returns false?

0 votes
265 views
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:

$('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.

Related Questions

+4 votes
5 answers 2,234 views
+1 vote
1 answer 678 views
+1 vote
1 answer 740 views
+1 vote
2 answers 93 views
+2 votes
1 answer 209 views
+1 vote
1 answer 80 views
+3 votes
1 answer 2,510 views
+1 vote
1 answer 130 views
asked in Programming by amit_pammu Expert (5,030 points)
+1 vote
1 answer 148 views

Not a Member yet?

Ask to Folks Login

My Account
533 Folks are online
60 members and 473 guest online
Your feedback is highly appreciated