• jQuery Video Tutorials

jQuery Misc index() Method



The index() method in jQuery is used to find the index position of an element within its sibling elements.

It is commonly used to determine the position of an element in a set of matched elements. This method returns an integer representing the index position of the element, starting from 0. If the element is not found, it returns -1.

Syntax

Following is the syntax of this method to get the (index position of the first matched selected element relative to its sibling elements) −

$(selector).index()

Following is the syntax of this method to get the (index position of an element, relative to the selector) −

$(selector).index(element)

Parameters

Here is the description of the above syntax −

  • element (optional): A DOM element, a jQuery object, or a selector string representing the element to find.

Example 1

In the following example, we are using the jQuery Misc index() method to get the index position of the clicked list item among its siblings −

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("li").click(function(){
                var index = $(this).index();
                alert("Index of clicked list item: " + index);
            });
        });
    </script>
</head>
<body>
    <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
        <li>Item 4</li>
    </ul>
</body>
</html>

After executing the above program, the index value of the clicked item will displayed through alert.

Example 2

Here, we are retreiving the index position of a specific element within a set of matched elements −

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            var listItems = $("li");
            var specificItem = $("#item3");
            var index = listItems.index(specificItem);
            alert("Index of the specific item: " + index);
        });
    </script>
</head>
<body>
    <ul>
        <li id="item1">Item 1</li>
        <li id="item2">Item 2</li>
        <li id="item3">Item 3</li>
        <li id="item4">Item 4</li>
    </ul>
</body>
</html>

After executing the above program, the element with id = "item3" will be retreived and displays it through alert.

jquery_ref_miscellaneous.htm
Advertisements