views:

56

answers:

4

Consider this:

<div class="test">one</div>
<div class="test">two</div>

<script>

var i1 = $('.test');
var i2 = $('.test');

console.log( i1 == i2 );
console.log( i1 === i2 );
console.log( i1.is(i2) );

</script>

They all print false although they contain the same elements. One would think that .is() would work for comparing but it doesnt. How would you compare two jQuery objects?

+1  A: 

i1 and i2 are distinct objects created by the jQuery constructor. The elements inside you can compare if you wish.

i1[0] == i2[0].

You can create a function to iterate through the entire element to compare and make sure the elements match up.

You could also do .is('.test') but you'd always have to specify the selector.

meder
Is there a clever way of looping and comparing?
David
A: 

They aren't the exact same. You're comparing the same element, but they are different nonetheless.

The .is() call must also fail, because element i1 does not match i2. You could use .is() to check for the class name for instance:

i1.is('.text') === true

update

because of your comment, http://www.jsfiddle.net/htcxT/

You are maybe even looking for the .unique() jQuery method, which which removes duplicated DOM elements from an array: .unique()

jAndy
Different how? I'm not looking to compare class names, I want to check if the objects contain the same DOM elements.
David
`i1.is('.text')` returned false on the console...
Reigel
@David: That's a different story, just to compare the `DOM elements` you have to compare them with `if(i1[0] === i2[0])` or `if(i1.get(0) === i2.get(0))`. Both patterns return the underlaying `DOM node` from the `jQuery object`
jAndy
@Reigel: You're doing anything wrong then. `.is('.text')` returns true, if the class `text` is applied.
jAndy
Ahh my bad, I use the `.test` of the OP... yours was `.text`... :)
Reigel
+2  A: 

i1 and i2 are not equal because they are different objects.

Sounds like what you're wanting is to find out if the elements in both the jQuery objects are the same elements.

You'd have to iterate over the numeric contents of both these objects and compare them instead.

For instance, something like:

for (var i = i1.length; i--;) {
  if (!i2[i] || i2[i] !== i1[i]) {
    // jquery objects don't contain same elements
  }
}
thomasrutter
+2  A: 

We can use .not()

var i1 = $('.test'); 
var i2 = $('.test');
alert(i1.not(i2).get().length == 0); //alerts true
Marimuthu Madasamy
Thats it. I used `!i1.not(i2).length` and it seems to work fine.
David
+1 cleaver idea!
Reigel
I think this would fail if i2 has more elementes that i1, giving a TRUE where FALSE was expected
alcuadrado
yeah.. should check first if `i1.length === i2.length`
Reigel