0

I have a problem with indexing elements after adding specific class. I need indexing not from first element of ul, but from li with class activated. Is it possible?

function setdataindex() {
  $('.ul li').removeAttr('data-index');
  $('.ul li.activated').each(function() {
    var index = $(this).index();
    $(this).find('span').html(index);
  });
}
setdataindex();

$('form').on('change', function() {
  var nodeActive = $(this).find('input:checked').attr('id');
  $('.ul li').removeClass('activated');
  $('.ul li span').empty();
  $('.ul').find('[data-node="' + nodeActive + '"]').addClass('activated');
  setdataindex();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form>
  <p><input id="nd1" type="radio" name="node" value="node1">Node1 </p>
  <p><input id="nd2" type="radio" name="node" value="node2">Node2 </p>
</form>

<ul class="ul">
  <li data-node="nd1">Test <span></span></li>
  <li class="activated" data-node="nd2">Test <span></span></li>
  <li data-node="nd1">Test <span></span></li>
  <li data-node="nd1">Test <span></span></li>
  <li data-node="nd2">Test <span></span></li>
</ul>

1
  • 2
    Please be more articulative .. what is the expected output ?Else people will not spend much time on your question Commented Sep 26, 2017 at 15:17

1 Answer 1

1

jQuery foreach method pass index and value to the callback:

function setdataindex() {
  $('.ul li').removeAttr('data-index');
  $('.ul li.activated').each(function(index) {
    $(this).find('span').html(index);
  });
}
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.