Skip to content
Advertisement

To find Next element data-id of list in JQuery

How to get the data-id of next list element from the current active list element on button click?

 <div class="nbrs">
    <ul>
      <li id="item1" data-id="1" class="active">Coffee (first li)</li>
      <li id="item2" data-id="2">Tea (second li)</li>
      <li id="item3" data-id="3">Green Tea (third li)</li>
    </ul>
    </div>

   <button id="btnNext" type="button">Next</button> 

The next element data-id need to be shown till the last (third) li.

Advertisement

Answer

You can find next li with .next('li') and find its attribute data-id value with .attr('data-id'). Remove active class from currently active li with $('li.active').removeClass('active'); & add active class in next li with next.addClass('active');.

Try like below.

$('#btnNext').click(function() {
  // find next li from currently active li
  let next = $('li.active').next('li');
  if (next.length > 0) {
    // remove active class from currently active li
    $('li.active').removeClass('active');
    // add active class in next li
    next.addClass('active');
    // get data id from next li
    let dataId = next.attr('data-id');
    alert(dataId);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<div class="nbrs">
  <ul>
    <li id="item1" data-id="1" class="active">Coffee (first li)</li>
    <li id="item2" data-id="2">Tea (second li)</li>
    <li id="item3" data-id="3">Green Tea (third li)</li>
  </ul>
</div>

<button id="btnNext" type="button">Next</button>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement