Reputation: 1
If i am indexing some elements like this:
$('#test_form li').each(function(index) {
$(this).addClass('option-nr-' + index);
});
how can i use the index number again in the next step to say something like:
if ($('#test_form li').hasClass('option-nr-[index]')){
// do somethin
}
?
Upvotes: 0
Views: 39
Reputation: 21485
Since in the first step you created a specific classname for the element, you can just use that classname as a selector; no need for the if
statement at all:
$('#test_form li.option-nr'+index) // will match that specific single element, chain anything you like onto this
Depending on what you're doing with this, though, it may make more sense to not add specific classnames to each element, and just operate on them by index in the first place. Specific identifiers are only necessary if the elements are going to change order or have new elements inserted or deleted from the list, and you need to be able to keep track of them individually. If you're only ever operating on the list as a list, you can just do this sort of thing when you need to match a specific element, and get the same results without having to add and keep track of a lot of extra classnames:
// these are equivalent:
$('#test_form li').eq(index)
$('#test_form li:eq('+index+')')
If you are going to add specific identifiers to each element, it would probably be better to add IDs rather than classnames: you'd get a small performance improvement (IDs are faster to look up), but more importantly it's just easier to keep track of what's what as you're reading the code if IDs are always unique and classnames aren't.)
Upvotes: 1