Zhurka
Zhurka

Reputation: 55

Get index of element after adding class

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>

Upvotes: 0

Views: 68

Answers (1)

Peter
Peter

Reputation: 1822

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);
  });
}

Upvotes: 1

Related Questions