Jquery gets the index of example

  • 2020-03-30 01:41:56
  • OfStack

Jquery gets index() method:

Jquery's index() method searches for matched elements and returns the index value of the corresponding element, counting from 0.

If you do not pass an argument to the.index() method, the return value is the position of the first element in the jQuery object collection relative to its peer.
If the argument is a set of DOM elements or jQuery objects, the return value is the position of the element passed relative to the original collection.
If the argument is a selector, the return value is the position of the original element relative to the selector in the matched element. If no matching element can be found, -1 is returned.
 
<ul> 
<li id="foo">foo</li> 
<li id="bar">bar</li> 
<li id="baz">baz</li> 
</ul> 

$('li').index(document.getElementById('bar')); //1. Pass a DOM object and return its index position in the original collection
$('li').index($('#bar')); //1. Pass a jQuery object
$('li').index($('li:gt(0)')); //1. Pass a set of jQuery objects and return the index position of the first element in the object in the original collection
$('#bar').index('li'); //1. Pass a selector to return the leading position of #bar in all li
$('#bar').index(); //1, returns the index position of the element in the peer without passing an argument.

Jquery gets an example of the element index value index()
 
//For secondary or tertiary linkage

<div id="nav"> 
<a href="http://www.51xuediannao.com/"> Website building material </a> 
<a href="http://www.51xuediannao.com/">jquery The special effects </a> 
<a href="http://www.51xuediannao.com/"> Lazy people host </a> 
<a href="http://www.51xuediannao.com/qd63/"> Front end of the road </a> 
</div> 

$("#nav a").click(function(){ 

//Four classic USES
var index1 = $("#nav a").index(this); 
var index2 = $("#nav a").index($(this)); 
var index3 = $(this).index() 
var index3 = $(this).index("a") 
alert(index3); 
return false; 
}); 

Related articles: