jQuery Difference Between .eq(count) and [count]

In my further understanding of jQuery, what is the difference between:

var allDivs = jQuery('div');
for( var count = allDivs.length - 1; count >= 0; count-- ) {
    var elem = allDivs.eq(count);
    if( elem.css('margin-left') == '-15px' ) {
        elem.css({'margin-left':'0'});
    }
}

And:

var allDivs = jQuery('div');
for( var count = allDivs.length - 1; count >= 0; count-- ) {
    var elem = allDivs[count];
    if( elem.css('margin-left') == '-15px' ) {
        elem.css({'margin-left':'0'});
    }
}

Answer

allDivs.eq(count) will return a jQuery object that contains the element that you specified.

allDivs[count] will return the DOM element object that you specified, so you won’t be able to use the css method on it, as that is a jQuery method.

Using $(allDivs[count]) gives the same result as allDivs.eq(count) (at least as long as count specifies an element that exists in allDivs).

Leave a Reply

Your email address will not be published. Required fields are marked *