Home >Web Front-end >Front-end Q&A >What is the usage of index in jquery
In jquery, the index() method is used to return the index position of a specified element relative to other specified elements. The element can be specified through the jquery selector and DOM element. If the specified element is not found, this method returns The result is "-1" and the syntax is "element object.index()".
The operating environment of this tutorial: windows10 system, jquery3.2.1 version, Dell G3 computer.
The index() method returns the index position of the specified element relative to other specified elements.
These elements can be specified via jQuery selectors or DOM elements.
Note: If the element is not found, index() will return -1.
Get the index position of the first matching element relative to its sibling elements.
Syntax
$(selector).index()
Get the index position of the element relative to the selector.
This element can be specified via a DOM element or a jQuery selector.
Syntax
$(selector).index(element)
The example is as follows:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>123</title> <script src="js/jquery.min.js"> </script> <script> $(document).ready(function(){ $("li").click(function(){ alert($(this).index()); }); }); </script> </head> <body> <p>点击获取列表项的索引位置,相对于它的兄弟元素</p> <ul> <li>Coffee</li> <li>Milk</li> <li>Soda</li> </ul> </body> </html>
Output result:
Click on the first li The element output result is:
Related video tutorial recommendations: jQuery video tutorial
The above is the detailed content of What is the usage of index in jquery. For more information, please follow other related articles on the PHP Chinese website!