JQuery. closest (), parent (), parents () Find the parent node _ jquery

Source: Internet
Author: User
See the Introduction to the closest () method in the 50 required practical jQuery code segments. Considering the need to find a father often in the development process, we used parent () parents () in the past () method (not found frequently !), So let's make a comparison! HTML code, test address: jQuery traversal-closest () method

------ When I stick the code up, it will be automatically hidden on the page (it will be displayed )! Who can teach me how this is swollen!
1. Search level-3 through item-1 (find the upper-level directly)

The Code is as follows:


$ ('Li. item-1 '). closest ('ul ')
$ ('Li. item-1 '). parent ()
$ ('Li. item-1 '). parents (). eq (0)


2. query level-2 through item-1 (query parent element through selector)

The Code is as follows:


$ ('Li. item-1 '). closest ('. level-2 ')
// $ ('Li. item-1 '). parent ('. level-2 ') // No. The parent () method traverses only the previous layer!
$ ('Li. item-1 '). parent (). parent () // This is too many!
$ ('Li. item-1 '). parents ('. level-2 ')


Usage of selector in parent (selector)

The Code is as follows:


$ ('Lil'). parent () // returns a set of level-3, level-2, and level-1. They are both the parent elements of li.
$ ('Lil'). parent ('. level-3') // filter level-3 from the preceding collection.


3. The closest method traverses from the current element, while parent () starts from the parent element!
$ ('Li. item-1 '). closest ('lil') // return item-1. Be sure to use it. If a p is nested in one p, you should consider correct use of the selector!
4. The use of the context parameter in closet (selector, context) traverses from the current element to the end of the context element. If the context parameter does not exist, it traverses to the root node.
The context parameter can improve the query efficiency!

The Code is as follows:


Var listItemII = document. getElementById ('II'); // Item-ii
// Var listItemII = $ ('# II'). This cannot be done. It has been confusing for a long time!
$ ('Li. item-1 '). closest ('U', listitemiiw.css ('background-color', 'red ');
// The result must be the parent ul element of item-1 and the child element of itemII,
$ ('Li. item-1 '). closest (' # one', listitemiiw.css ('background-color', 'green ');
// The id = one element of item-1, which must be a child element of itemII, not found


5. Analyze context parameters

The Code is as follows:


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 )){
// If the matching element is found, add it to the returned value set! Jump to the next element to search
Ret. push (cur );
Break;
} Else {
Cur = cur. parentNode;
// Traverse the DOM tree up and match the selector
// If the parent node does not exist during the above process, the root node does not exist or the context node is found (the specified location has been reached )!
If (! Cur |! Cur. ownerDocument | cur === context | cur. nodeType === 11 ){
Break;
}
}
}
}
Ret = ret. length> 1? JQuery. unique (ret): ret;
Return this. pushStack (ret, "closest", selectors );
}


I am not very familiar with JQuery source code, and I will not explain some details here!
The definition of closest () shows that the variable cur = this [I] Compared with context is a DOM object, while $ ('# II ') the method is a JQuery object, so the context parameter passed to the closest (selector, context) method must be obtained through the DOM method!
Conversion between jQuery objects and DOM objects?
1. Get the object (add $ before the variable name to distinguish JQuery from DOM variables ):
Get jQuery object: var $ variable = jQuery object;
Get the DOM object: var variable = DOM object;
2. Convert jQuery objects to DOM objects:
Convert var cr = $ ("# cr") [0] Using arrays;
Use the get (index) method to convert var cr = $ ("# cr"). get (0 );
3. convert a DOM object to a jQuery object:

The Code is as follows:


Var cr = document. getElementsById ("cr"); // get the DOM object
Var $ cr = $ (cr); // convert to jQuery object


SO ....
$ ('Li. item-1 '). closest (' # one', $ ('# II'). get (0) // used in this way
You can also change the "cur = context" judgment in the source code to "$ (cur) = $ (current)", so that it can be compatible with the two usage methods!
Of course, modifying the source code is not a good suggestion, but why does JQuery not use this method ...... Please advise !!!
Related Article

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.