chris barr

Photo/Dev/Design

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>