Use of JQ index() function

The index() function is used to get the index value of the specified DOM element in the current jQuery object.
Syntax: jQueryObject.index( [ object ] )
The object here refers to: optional /String/Element/jQuery type represents the object of the specified element.

The return value of the index() method is of type Number, which returns the index position of the specified element (starting from 0).
Note: The current element in the text description below represents the first element of the current jQuery object.
If no parameter object is specified, returns the index position of the current element among all its siblings.
If object is of type String, it is regarded as a selector and returns the index position of the current element in the element matched by the selector. Returns -1 if the selector does not match any elements or the current element is not within the matched elements.
If object is a DOM element or a jQuery object, returns the index position of the element (or the first element in the jQuery object) in the element matched by the current jQuery object.

 

<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="n1">
    <div id="n2">
        <span id="n3"></span>
        <ul id="n4">
            <li id="n5">item1</li>
            <li id="n6">item2</li>
            <li id="n7">item3</li>
        </ul>
        <span id="n8"></span>
    </div>  
</div>
<script type="text/javascript" src="jquery-1.10.1.min.js"></script>
<script>
// Omit parameter: return the index of the first li element among all sibling elements
console.info($("li").index());//0

// The parameter is a DOM element: returns the index of n6 in $li
console.info($("li").index(document.getElementById("n6")));//1

// The parameter is a jQuery object: returns the index of $("#n7") in $li
console.info($("li").index($("#n7")));//2

// The parameter is the selector string: returns the index of the first element in $li (that is, n5) in the element matched by the selector "#n4"
// The selector "#n4" matches only one element n4, not n5, so return -1
console.info($("li").index("#n4"));//-1

// Omit the parameter: the index of n4 in the sibling element, the sibling element before n4 has an n3, so the return index is 1
console.info($("#n4").index());//1

// Argument is the selector string: the index of n8 in the element matched by the selector "span"
// The selector "span" matches two elements n3, n8, n8 is the second element, so the return index is 1
console.info($("#n8").index("span"));//1

</script>
</body>
</html>

 

Effect picture:

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326992891&siteId=291194637