Search for given element from among the matched elements.
*This signature does not accept any arguments. --- .index()
*A selector representing a jQuery collection in which to look for an element. ---.index(selector)
*The DOM element or first element within the jQuery object to look for. ---.index(element)
If a selector string is passed as an argument,.index() returns an integer indicating the position of the first element within the jQuery object relative to the elements matched by the selector.If the element is not found,.index() will return -1.
The difference between .get() and .index()
.get(),which accepts an index and returns a DOM node
.index(),can take a DOM node and returns an index.
<body>
<p id="h1">H1</p>
<p id="h2">H2</p>
<p id="h3">H3</p>
<script src="jquery-3.1.1.js"></script>
<script>
var listItem = document.getElementById("h3");
alert("Index: "+$("p").index(listItem));
</script>
Index: 2
Similarly , if we retrieve a jQuery object consisting of one of the three list items,.index() will search for that list item:
<body>
<p id="h1">H1</p>
<p id="h2">H2</p>
<p id="h3">H3</p>
<script src="jquery-3.1.1.js"></script>
<script>
var listItem = $('#h2');
alert("Index:"+$("p").index(listItem));
</script>
Index:1
Note that if the jQuery collection used as the .index() method's argument contains more than one element, the first element within the matched set of elements will be used.
<body>
<p id="h1">H1</p>
<p id="h2">H2</p>
<p id="h3">H3</p>
<p id="h4">H3</p>
<script src="jquery-3.1.1.js"></script>
<script>
var listItem = $("p:gt(1)");
alert("Index: "+$("p").index(listItem));
</script>
If we use a string as the .index() method's argument, it is interpreted as a jQuery selector string.The first element among the object's matched elements which also matches this selector is located.
<body>
<p id="h1">H1</p>
<p id="h2">H2</p>
<p id="h3">H3</p>
<p id="h4">H3</p>
<script src="jquery-3.1.1.js"></script>
<script>
var listItem = $("#h3");
alert("Index:"+listItem.index("p"));
</script>
Examples:
<span>Hello World</span>
<p>First P</p>
<p>Second P</p>
<p>Third P</p>
<p>Fourth P</p>
<script src="jquery-3.1.1.js"></script>
<script>
$("p").click(function () {
var index =$("p").index(this);
$("span").text("That was p index #"+index);
})
</script>
:gt() Selector
Selector all elements at an index greater than index within the matched set.
index: Zero-based index. --- (":gt(index)")
indexFormEnd: Zero-based index. counting backwards from the last element.
:lt() Selector
Select all elements at an index less than index within the matched set.