Home  >  Article  >  Web Front-end  >  How to use index() method in jquery

How to use index() method in jquery

WBOY
WBOYOriginal
2022-04-02 15:17:272057browse

In jquery, the index() method is used to return the index position of a specified element relative to other specified elements, or to obtain the index position of an element relative to a selector. The syntax is "$(selector).index() ” or “$(selector).index(element)”.

How to use index() method in jquery

The operating environment of this tutorial: windows10 system, jquery3.2.1 version, Dell G3 computer.

How to use the index() method in jquery

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.

Query provides an index() method

Search for elements that match the object represented by the parameter, and return the index value of the corresponding element.

If a matching element is found, return starts from 0; if no matching element is found, -1 is returned.

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="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    alert($(".hot").index($("#favorite")));
  });
});
</script>
</head>
<body>
<p>单击按钮来获得id =“favorite”的元素的索引,相对于jQuery选择器(类=“hot”):</p>
<button>获取下标</button>
<ul>
<li>Milk</li>
<li class="hot">Tea</li>
<li class="hot" id="favorite">Coffee</li>
</ul>
</body>
</html>

Output result:

How to use index() method in jquery

After clicking the button:

How to use index() method in jquery

Recommended related video tutorials: jQuery video tutorial

The above is the detailed content of How to use index() method in jquery. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn