Are jQuery objects of the same element not equal?

It should be something that I'm missing, but please look at the next page and JavaScript and tell me why, for all that is holy, jQuery will not return true?

HTML: http://alcatel.scottbuckingham.com/reporting/test.html

<p class="test">hello1</p> 

JS: http://alcatel.scottbuckingham.com/reporting/_scripts/collapse.js

 ;(function($, window, document, undefined) { var t = $('.test'); var s = $('.test'); console.log(t); console.log(s); if (t === s) { console.log('yes'); } })(jQuery, window, document); 

I literally spent hours trying to figure it out, and reduced it to almost almost 1 === 1 , which would not work.

Any help is much appreciated!

+8
jquery
source share
5 answers

Try this - Working Demo -> http://jsfiddle.net/mohammadAdil/tHjgN/

  if(t.is(s)) { console.log('yes'); } 

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

Or with ===

 if (t.get(0) === s.get(0)) { //<--Compare DOM elements instead of jquery object's console.log('again yes'); } 

Demo → http://jsfiddle.net/mohammadAdil/tHjgN/1/

+8
source share

You can use jQuery is method.

Description. Check the current set of elements with a selector, element or jQuery object and returns true if at least one of these elements matches the given arguments.

 if (t.is(s)) { console.log('yes'); } 

Sample script: http://jsfiddle.net/IrvinDominin/q86Sh/

+2
source share

You can do this by comparing HTML nodes. What if you want to compare HTML objects, this is the right way to do this.

 if (t[0] === s[0]) { console.log('yes'); } 
+1
source share

You had a script in <head> , but the <p class="test">hello1</p> element in <body> .

First you must use $(document).ready() to make sure the content is loaded. Then check if they are equal with .is() .

 $(document).ready(function() { var t = $('.test'); var s = $('.test'); console.log(t); console.log(s); if (t.is(s)) { console.log('yes'); } }); 

Compare examples with and without .ready() .

+1
source share

This may help you:

 var test = document.getElementById('test') //returns a HTML DOM Object var test = $('#test') //returns a jQuery Object var test = $('#test')[0] //returns a HTML DOM Object 

So (for example, as you said), use this:

 if (t[0] === s[0]) { console.log('yes'); } 

It is also recommended to use

 $(document).ready(function(){ }); 

around your code.

+1
source share

All Articles