So I'm trying to cycle through the members of "someclass", not the DOM elements but their jQuery count开发者_StackOverflow社区erparts. I've been using $($(".someclass")[i]), but this is pretty ugly. Is there a more natural way to do this?
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.
Use .each()
[docs] for iterating over the element:
$(".someclass").each(function() {
// use $(this)
});
You can use nth-child of jquery.
$("ul li:nth-child(1)").addClass("green"); //this select 1 the element of group
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>";
});
Try :
$(".someclass:eq("+yourNumberHere+")")
精彩评论