JQuery selector row index function

As I know from jQuery training, you can use the jquery function index:

  • .index() // without arguments
  • .index(domObject) // argument is a dom object
  • .index(JqueryObject) // An argument is a jQuery object
  • .index("selectorString") // the argument is a selector string

I am testing an index function with an argument - a selector string.

html → body:

 <div class="name" id="id1"> <h2>Z</h2> <h2>X</h2> </div> <div class="name" id="id2"> <h2>A</h2> <h2>B</h2> </div> 

Jquery scripts:

 var index1 = $('.name').index("#id1"); var index2 = $('.name').index("#id2"); alert(index1); alert(index2); 

Results: 0 for index1 (correct) and -1 for index2 (incorrect).

So the question is: why can't I get the correct div # id2 index value?

jsfiddle: http://jsfiddle.net/GhPxD/60/

+6
source share
3 answers

There are no errors, the API is just ... weird. Here's the documentation :

If .index () is called in the collection of elements and the DOM element or the jQuery object is passed to, .index () returns an integer indicating the position of the passed element relative to the original set.

If a selector string is passed as an argument, .index () returns an integer indicating the position of the first element in the jQuery object relative to the elements corresponding to the selector. If the item is not found, .index () will return -1.

So you want

 $('#id2').index(".name"); 

If this function behaves differently, a very confusing IMO.

+2
source

You can pass the jquery object in the index method to make this work:

 var index = $('.name').index($("#id2")); 

Working demo

0
source
 statement 1 : var index1 = $('.name').index("#id1"); statement 2 : var index2 = $('.name').index("#id2"); 

expression 1 1. As you know, when you use any selector in jquery, it returns the first matching element 2. Now you are trying to find the index index("#id1") so that it is found successfully at index 0, so it return 0

expression 2 1. As you know, when you use any selector in jquery, it returns the first matching element 2. Now you are trying to find the index index("#id2") so that it cannot find the child element with #id2 so that he reurn -1

-1
source

Source: https://habr.com/ru/post/980576/


All Articles