DOM method index () (Why $ (this). Index (this) is incorrect)

Source: Internet
Author: User

The index () method returns the index position of the specified Element relative to other specified elements.

Full Syntax: $ (Selector). Index (Element), Where element is an optional parameter.

1. If the element is omittedObtain the index position of the First Matching Element relative to its compatriot element..

For example, in the following code:


$ (This ). index (); $ (this) indicates the clicked Li element. The index () is the Li element (which is the first element matching itself) the index value relative to its compatriot element. This is correct and is the result we need.

If it is written as $ ('ul li '). index (); then the output value is 0, because $ ('ul li '). index () is the index value of the first matched element under the Li element relative to the compatriot element, that is, 0th elements.


2. The element is not omitted.

Or the above Code. If it is changed to $ (this). Index (this), all output values are 0.

This is because $ (Selector). Index (Element),Is to obtain the index position of the element relative to the selector.

That is to say, if $ (this). Index (this) is written like this, we obtain the position of the current click Li relative to itself, that is, 0.


If it is written as $ ('ul li '). index (this) is acceptable, because the position of the clicked Li element relative to the Li element under the UL selected by the selector is obtained, so the correct index value can be obtained.



In summary, we know $ (this ). index () = $ ('ul li '). index (this), the two methods in our context can correctly obtain the index value of the element.

In this case, we still have a question about the selector and this.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.