In JS we want to get the parent node there are many ways, such as
1) Parentobj.firstchild: This method can be used if the node is the first child node of a known node (parentobj). This property can be recursively used, that is, support parentObj.firstChild.firstChild.firstChild ... The form so that you can get deeper nodes.
(2) Parentobj.lastchild: Obviously, this property is the last child node to get a known node (parentobj). As with FirstChild, it can also be used recursively.
In use, if we combine the two, we will achieve more exciting effects, namely: ParentObj.firstChild.lastChild.lastChild ...
(3) Parentobj.childnodes: Gets an array of child nodes of a given node, which can then be found by looping or indexing the desired node.
In jquery we can use closest and parents
Suppose you need to get the grandparent node of the current node (the parent node's parent node), which has attributes class= "pp", the method obtained is:
| The code is as follows |
Copy Code |
$ (' #cur '). Parent (). parent (); Or $ (' #cur '). Parent (). Parent ('. pp '); Or $ (' #cur '). Parent ('. pp '); |
Gets the method closest ([expr]) of the parent node.
| The code is as follows |
Copy Code |
$ (' #cur '). Closest ('. pp '); |
Let me give you an example,
| The code is as follows |
Copy Code |
<ul class= "Parent1" > <li><a href= "#" id= "Item1" >jquery Get parent node </a></li> <li><a href= "#" >jquery Get parent element </a></li> </ul> |
Our goal is to use the ID of item1 note A to the class for the Parent1 UL elements, there are several ways:
1. Parent ([expr])
Gets a collection of elements that contains the unique parent element of all matching elements.
You can use an optional expression to filter.
The code is as follows
| The code is as follows |
Copy Code |
$ (' #item1 '). Parent (). Parent ('. Parent1 '); |
2.:p arent
Matches elements that contain child elements or text
The code is as follows
| The code is as follows |
Copy Code |
| $ (' li:parent '); |
3. Parents ([expr])
Gets a collection of elements that contain the ancestor elements of all matching elements (without the root element). You can filter by an optional expression.
The code is as follows
| The code is as follows |
Copy Code |
$ (' #items '). Parents ('. Parent1 '); |
The main differences between closest and parents are:
The former matches the search from the current element, the latter starting from the parent element to find
The former is searched up until a matching element is found, the latter is searched up until the root element, and then the elements are placed in a temporary set and then filtered with the given selector expression.
The former returns 0 or 1 elements, which may contain 0, 1, or more elements