0

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?

0

4 Answers 4

3

We can use .not()

var i1 = $('.test'); 
var i2 = $('.test');
alert(i1.not(i2).get().length == 0); //alerts true
Sign up to request clarification or add additional context in comments.

3 Comments

Thats it. I used !i1.not(i2).length and it seems to work fine.
I think this would fail if i2 has more elementes that i1, giving a TRUE where FALSE was expected
yeah.. should check first if i1.length === i2.length
2

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
  }
}

Comments

1

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.

1 Comment

Is there a clever way of looping and comparing?
0

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()

4 Comments

Different how? I'm not looking to compare class names, I want to check if the objects contain the same DOM elements.
@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
@Reigel: You're doing anything wrong then. .is('.text') returns true, if the class text is applied.
Ahh my bad, I use the .test of the OP... yours was .text... :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.