Comparing jQuery objects

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>

   

4 replies

  1. Bajki says:

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

  2. alex says:

    great tip mate!

  3. Sébastien BEIRNAERT says:

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

  4. Charles says:

    Thanks for this usefull tip, I was looking for this precise answer.

Leave a Reply