When I used jquery's parents () to find the parent-level element to delete it, I found that it does not contain the root element, so I used closest (). The effect is good, but there is a difference between the two, see: & amp; lt; ul & amp; nbsp; class = & quot; box & quot; & amp; nbs
When I used jquery's parents () to find the parent-level element to delete it, I found that it does not contain the root element, so I used closest (). The effect is good, but there is a difference between the two, see:
Hello Moto
To obtain the parent element LI of class = "moto", you can use $ (". moto"). parent (). parent (). But it is complicated,
There are two other methods to obtain a parent Tag: parents () and closest ().
Parents () method:
Parents (), I think you are not familiar with it anymore. It is used to obtain all the qualified ancestor elements (Excluding itself), This is a set.
Here, we can:
$ (". Moto"). parents ("li [name = 'B']");
Or
$ (". Moto"). parents (". li_moito ");
Closest () method:
Closest (), this method is to check the elements and perform step-by-step matching. First, it will match from itself
If the task is not successful, it is searched up until the matching selector is found. If not, an empty object is returned.
You can write as follows:
$ (". Moto"). closest ("li [name = 'B']");
Or
$ (". Moto"). closest (". li_moito ");
Distinguish parents () from closest ()
1. The former matches elements from the parent level, and the latter starts from itself.
2. The former searches up all parent-level elements until the root element, and then places the search results to a temporary
And then filter by the rated conditions. The latter searches up from its own elements until a valid matching element is found.
3. The former can return 0 or 1 element values, or multiple elements. The latter can only have 0 or 1 element value;
Therefore, you need to use parents () and closest () as needed ().