0

When I assign a jquery element to a variable, it won't match the element in a comparison, but when I assign a javascript element it will...

test1 =  $(".the_div");
console.log(test1 ==  $(".the_div"));
// logs false


test2 = $(".the_div")[0];
console.log(test2 == $(".the_div")[0]);
// logs true

What's going on? Why this happens?

sigmaxf
  • 7,998
  • 15
  • 65
  • 125
  • Well, `test1[0] == test1[0]` would yield true as well… – Bergi Dec 03 '15 at 07:39
  • Both collections contain the exact same element. Still, the two collections are two separate objects with their own identities. – Bergi Dec 03 '15 at 07:42

1 Answers1

0

test1 is an Object, and you cannot compare two objects using comparison operators. To compare two jQuery objects use is() as shown in jQuery object equality

test2 is a String. By appending [0] to the jQuery object will return the outerHTML of the first element in the set.

See What does $(selector)[0] mean in jQuery?

Community
  • 1
  • 1
Tushar
  • 85,780
  • 21
  • 159
  • 179
  • 1
    `test2` is not a string. – Bergi Dec 03 '15 at 07:39
  • 1
    Can you detail your first statement, please? `test1 == test1` is easily comparable (and even yields `true`). – Bergi Dec 03 '15 at 07:40
  • @Bergi `test1` is jQuery Object so it cannot be compared using `==`. `test2` is string, `[0]` will return the outerHTML of the matched element, Check [this](http://stackoverflow.com/questions/32783869/what-does-selector0-mean-in-jquery/32783887#32783887) – Tushar Dec 03 '15 at 08:31
  • Your [own answer there](http://stackoverflow.com/a/32783887/1048572) says "*`[0]` […] will return the first DOM element*" - which is correct. DOM element, not outerHTML. It's an object, not a string. – Bergi Dec 03 '15 at 15:46