Compare two jQuery objects


#1

Hey all,

Just wanted to share my findings after about an hour and a half of trial and error. First a bit of background: I was working on a project which had an array of jQuery objects, and I needed to find out if a given object was in that array (and then remove it). At first I used the indexOf, but it failed. Then I tried using jQuery’s $.inArray function, but that also didn’t work. I then remember the problem of $(’#div1’) == $(’#div1’) returns false. I then tried using the syntax of $(’#div1’).is(’#div1’) and that worked, but that wouldn’t work for me. Since I didn’t have access to the selectors at runtime (and sometimes there would be a selector at all!) I needed to do something equivalent to $(’#div1’).is($(’#div1’)) but that doesn’t work at all. In fact, it causes a JavaScript error. After a bit of hunting around in the jQuery source, I found that a bit of hacking on the $().not() function would work. If you didn’t know, if you pass an element into .not, it will remove it from the selector. That means, if I did $(’#div1’).not($(’#div1’)), it would return []. Of course, if the second element was not fundamentally the same, it would return something. Finally, I had it! All I had to do now was check to see if $(’#div1’).not($(’#div1’)).length == 0 and I could tell if it was in the array. My final code, with the removal is the following:

$.each(list, function(index) {
	if(element.not(this).length == 0) {
		list.splice(index, 1);
	}
});

where list is the array and element is the thing to check for.

If somebody already knew this, or has a better way of accomplishing this please share, but I was just pretty happy with myself on this one and just wanted to share.


#2

If I understood you correctly, then you wanted to check whether something like $(’#div1’) was present in an array that contained similar jQuery objects. If that is really is the case, then I have seen that in order to compare two jQuery objects, you should do something like this

if( $('div.div1')[0] === $('div.div2')[0] ) {
    // the two objects are the same DOM element
}

Using the $(element)[0] syntax you are essentially gaining access to the DOM element which is being referenced by jQuery. And once you have the DOM element, then I have seen that you can compare two such DOM elements.

So for your particular case, to detect whether a jQuery object is present in an array of other jQuery objects you can do something like this:

$.each(list, function(index) {
    if( $(element)[0] === this ) {
        list.splice(index, 1);
    }
});

I hope this is what you were talking about.