0

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
  }

?

2
  • 1
    $('#test_form li').eq(index) Commented Apr 3, 2018 at 12:43
  • That looks like a mis-use of the class attribute to me. Classes are intended to apply to multiple elements, not for identifying unique ones. Commented Apr 3, 2018 at 12:56

1 Answer 1

1

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.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.