jquery parents () and closest () Introduction to usage and differentiation

Source: Internet
Author: User

Example 1

The code is as follows Copy Code

<ul class= "box" Name= "a" >

<li name= "B" class= "Li_moito" ><p><a href= "#" class= "moto" >hello moto</a></p></li >

</ul>


If you want to get the parent element Li for class= "moto", you can use $ (". Moto"). Parent (). Parent (). But more cumbersome,

There are two other ways to actually get the parent tag, namely parents () and closest ().


Parents () Method:

The method accepts an optional selector expression that is the same as the parameter type we pass to the $ () function. If this selector is applied, the element is filtered by detecting whether the element matches the selector.

Parents (), I think this is familiar to all, it is to get all the eligible ancestor elements (excluding itself), which is a collection.

Here, we can:

The code is as follows Copy Code

$ (". Moto"). Parents ("Li[name= ' B ')");

Or

$ (". Moto"). Parents (". Li_moito");

.. parents () is similar to the. Parent () method, unlike the latter traversing a single hierarchy up the DOM tree.


Consider this page with a basic nested list:

The code is as follows Copy Code

<ul class= "level-1"
  <li class= "Item-i" >I</LI>
  <li class= "Item-ii" > II
    <ul class= "Level-2"
      <li class= "Item-a" >a </li>
      <li class= "Item-b" >b
         <ul class= "level-3"
          <li class= "Item-1" >1</li>
          <li class= "Item-2" >2</li>
          <li class= "item-3" >3</LI>
         </ul>
      </li>
       <li class= "item-c" >C</LI>
    </ul>
  </li>
  <li class= "ITEM-III" >III</LI>
</ul>

If we start with Project A, we can find its ancestor elements:

The code is as follows Copy Code

$ (' li.item-a '). Parents (). CSS (' background-color ', ' red ');


Closest () method:

Closest (), this method is to check the elements up and to match. First, it is matched from itself, matched to


work returns itself; if unsuccessful, look up until a matching selector is found. If not, the empty object is returned.

You can write this:

The code is as follows Copy Code

$ (". Moto"). Closest ("Li[name= ' B ')");

Or

$ (". Moto"). Closest (". Li_moito");

The usage of the context parameter in closet (Selector,context) is traversed from the current element to the end of the element, if there is no context parameter
Traverse to root node

This shows that using the context parameter can improve query efficiency!

The code is as follows Copy Code


var listitemii = document.getElementById (' II '); Item-ii
var listitemii=$ (' #ii '), this is not good, puzzled for a long time!
$ (' li.item-1 '). Closest (' ul ', listitemii). css (' background-color ', ' red ');
The result must be the ITEM-1 's parent UL element, the itemii of the child element,
$ (' li.item-1 '). Closest (' #one ', listitemii). css (' background-color ', ' green ');
Item-1 id=one element, and must be a child element of itemii, not found

Analysis of 5.context parameters

The code is as follows Copy Code


Closest : function (selectors, context) {
var ret = [], I, l, cur = this[0];
//String
var pos = pos.test (selectors) | | | typeof selectors!== "string"?
JQuery (selectors, context | | this.context):
0;
for (i = 0, L = this.length i < l i++) {
cur = this[i];
while (cur) {
if (pos? Pos.index (cur) > -1:jquery.find.matchesselector (cur, selectors)) {
///Find a match element, add it to the return value collection! Jumps to the next element's lookup
Ret.push (cur);
break;
} else {
cur = cur.parentnode;
//Traversal of the DOM tree, matching selector
///In the above procedure if the parent node does not exist, the root node does not exist or the context node is found (reached the specified location)!
if (!cur | |!cur.ownerdocument | | | cur = = Context | | cur.nodetype = =) {
break;
}
}
}
}
ret = ret.length > 1 jquery.unique (ret): ret;
Return This.pushstack (ret, "closest", selectors);
}

Distinguish between parents () and closest ()

1. The former matches the element from the parent, and the latter begins with itself.

2, the former look up all the parent elements, until the root element, and then put the results of these lookups to a temporary

collection, which is filtered by the rated condition, which starts looking up from its own element until a valid matching element is found.

3, the former return element value can have 0, one, or multiple, the latter only 0 or 1;

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: info-contact@alibabacloud.com 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.