jQuery index()

Introduction

Get the index of the clicked <li> element, relative to its siblings:

Click the list items to get the index position, relative to its sibling elements.

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(){
  $("li").click(function(){
    document.getElementById("demo").innerHTML = $(this).index();
  });//  ww  w  .  j a v a  2s .c o  m
});
</script>
</head>
<body>

<p id="demo"></p>
<ul>
  <li>CSS</li>
  <li>HTML</li>
  <li>Javascript</li>
</ul>
</body>
</html>

The index() method returns the index position of specified elements relative to other specified elements.

The elements can be specified by jQuery selectors, or a DOM element.

If the element is not found, index() will return -1.

To get the index position of the first matched selected element relative to its sibling elements.

$(selector).index()

Get the index position of an element, relative to the selector.

The element can be specified using a DOM element, or a jQuery selector.

$(selector).index(element)
Parameter
Optional
Description
element

Optional.

the element to get the index position of.
Can be a DOM element or a jQuery selector



PreviousNext

Related