jQuery index() Get index relative to another element

Introduction

Click the button to get the index of the element with id="favorite", relative to the jQuery selector (class="hot").

View in separate window

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    document.getElementById("demo").innerHTML = 
       $(".hot").index($("#favorite"));
  });/* www  .  j  a v a2  s. com*/
});
</script>
</head>
<body>
<button>Get index</button>

<p id="demo"></p>

<ul>
  <li>HTML</li>
  <li class="hot">CSS</li>
  <li class="hot" id="favorite">Javascript</li>
</ul>

</body>
</html>



PreviousNext

Related