Comparing jQuery objects

Tuesday, July 21, 2009

Just wanted to post a quick blog update with a cool jQuery trick I’ve been using recently. Every now and then I need to compare one jQuery object to another but a simple $(this) == someObject doesn’t do anything. As it turns out jQuery objects are actually stored internally as an array and you can’t just directly compare arrays.

So with that in mind, the easiest and quickest solution is to just access the items in the array and compare those instead. Luckily the very first item in the jQuery array is all we need here, so to access it you simply need to put in square brackets the array item number you want like so: $(this)[0]. So check out the code example below.

<div id="nav">
    <a href="#">link 1</a>
    <a href="#">link 2</a>
    <a href="#">link 3</a>
    <a href="#">link 4</a>
</div>

<script type="text'javascript">
$(
    allItems = $("#nav a");  
    secondItem = $("#nav a:nth-child(2)");

    //loop through each item in this jQuery collection
    allItems.each(function(){
        //Compare the current jQuery object with the saved jQuery object
        //by accessing the first item in the array of each object.
        if($(this)[0] == secondItem[0]){
            //we are on the second item! Give it a red background
            $(this).css("background-color","red");
        }
    });
});
</script>

   

Posted by Chris Barr on 07/21 at 09:21 PM
Filed under General, Web, Code, Javascript
Comments
1
Bajki commented on Jul 24, 2009 at 02:31 am

As far as I’m not very advanced with html issues this tip could be helpful for me. So thanks.

2
alex commented on Oct 12, 2009 at 10:55 pm

great tip mate!

3
Sébastien BEIRNAERT commented on Jan 15, 2010 at 03:42 am

Thx so much
Helped me a lot to use JQuery in an OO context

Post a Comment