Skip to content Skip to sidebar Skip to footer

Iterate Over A Jquery Collection Without Having To Rebuild The Jquery Object

$('.item').each (i, elt) -> $(elt).attr('href') # ... Doing $(elt) is necessery to get the jquery object. Is there a way to iterate over a jquery collection, without ha

Solution 1:

Doing $(elt) is necessery to get the jquery object.

Yes.

Is there a way to iterate over a jquery collection, without having to rebuild the jquery object?

No. Because the jQuery object you have is a set of all of the matched elements. To use the jQuery methods on individual elements, you need to get a jQuery object containing just the individual element you want to act on. In a loop, that means wrapping your elt (or this, as both are the same DOM element).

For lots of things, though, you don't need jQuery methods. Your example is one of those things, just use elt.href directly:

$(".item").each (i, elt) ->
    var someVar = elt.href;
    # ...

The DOM2 HTML spec and the newer HTML5 spec both list lots of reflected properties you can use directly. id, for instance, is one in particular people frequently use. You see $(this).attr("id") a lot where this.id would be sufficient (and more efficient, although it's extremely rare that the efficiency matters).

Solution 2:

Yes, cache the jQuery object then select by index.

var $items = $(".item");

$items.each(function(i) {
    $items.eq(i).doStuff();
});

Post a Comment for "Iterate Over A Jquery Collection Without Having To Rebuild The Jquery Object"