jQuery index() method
The index() method is used to return the index value of the element with respect to the selector. The method will return -1 if the element is not found.
Index of the first matched element, relative to siblings
If no argument is passed to the index() method, the method will return an integer representing the position of the first element in the jQuery object relative to its siblings.
Index of an element, relative to selector
This method accepts an optional parameter, which is defined as follows -
element: This is an optional parameter that can be a jQuery selector or a DOM element. It specifies the element to get the index position of.
Suppose we pass a DOM element as an argument and using the index() method on the set of elements. In that case, the method will return an integer representing the position of the passed element relative to the original set.
On passing a selector string as an argument, the index() method will return an integer representing the position of the first element in the jQuery object relative to the elements matched by the selector.
In this example, we are using the index() method to get the index value of the paragraph elements. Here, we are using the method with or without arguments. So, on clicking the paragraph element, we will get the index of the corresponding paragraph according to the syntax. The index starts with 0.
Here, the color names are the paragraph elements.Test it Now
On clicking the paragraph, the index of the corresponding paragraph element will be displayed according to the syntax, as shown in the below screenshot.
As we can see the index of paragraph with id p1 is 0. This is because the index starts with 0.