⊗jqSeIM 72 of 113 menu

jQuery index method

If we need to find the number of an element in a set, we can use the index method.

We can display the position number of an element relative to its neighbors. For example, we have a numbered list:

<ol> <li>text</li> <li id="test">text</li> <li>text</li> </ol> <div>text</div>

Using the index method, we will now output the number div:

let num = $('div').index(); alert(num);

You can also additionally pass a selector. Consider the following HTML code:

<ol> <li id="first">text</li> <li id="test">text</li> <li>text</li> </ol> <div>text</div>

Now, in addition to the element tag name, we pass the name id to the parameters:

let num = $('li').index($('#test')); alert(num);

If no such element is found, the method will return -1.

Get the li number with #test using only the element tag name.

Get the number li with #first, also specifying the selector name.

byenru