Skip to content Skip to sidebar Skip to footer

Easier Way To Select Ith Jquery Object Of Group Than $($(".someclass")[i]))?

So I'm trying to cycle through the members of 'someclass', not the DOM elements but their jQuery counterparts. I've been using $($('.someclass')[i]), but this is pretty ugly. Is th

Solution 1:

You could use the eq() method:

$(".someclass").eq(i);

That said, Felix Kling is right: you'd better use each() instead of a loop to iterate over the elements stored in a jQuery object.

Solution 2:

Use .each() for iterating over the element:

$(".someclass").each(function() {
    // use $(this)
});

Solution 3:

You can use nth-child of jquery.

$("ul li:nth-child(1)").addClass("green"); //this select 1 the element  of group

Solution 4:

You can use the each method to iterate the elements:

$(".someclass").each(function(i, e){
  // i is the index// e is the element// this is the element// $(this) is the element wrapped in a jQuery object
  $(this).append("<span>" + (i+1) + "</span>");
});

(The parameters in the callback function is optional, as usual.)

Some methods for manipulating elements can take a callback method, so that you can use that to iterate the elements. Example:

$(".someclass").append(function(i, h){
  // i is the index// h is the current html content// Return html to append:return"<span>" + (i+1) + "</span>";
});

Solution 5:

Try :

$(".someclass:eq("+yourNumberHere+")")

Post a Comment for "Easier Way To Select Ith Jquery Object Of Group Than $($(".someclass")[i]))?"