JQuery obtains the parent element node, child element node, and sibling element node.
This document describes how jQuery obtains parent, child, and sibling nodes. We will share this with you for your reference. The details are as follows:
First, let's take a look at this html code. The entire method of taking nodes (parent, child, brother, etc.) is centered around this Code:
<Ul class = "par"> <li id = "firstli">
Obtain the JQUERY parent node:
Jquery has many methods to obtain parent elements, such as parent (), parents (), closest (), find, and first-child, which can help you find parent nodes, child nodes, and sibling nodes.
For example, we use parent () to obtain the parent node.
$ ("# Dwtedx "). parent (). parent (); // obtain the li node with the id firstli $ ("# dwtedx "). parent (). parent (". par "); // get the top ul node $ (" # dwtedx "). parent (". par "); // obtain the ul node above the first level. You can use the parent method to obtain the parent node. You can select a method based on your project needs.
Next, let's mainly talk about the differences between parents () and closest () methods.
1. closest matches the current element and parents matches the parent element.
2. closest goes up step by step until a matched element is found and the parents goes up until the root element is found. Then, these elements are put into a temporary set and then the given selector expression is used. filter
3. closest returns 0 or 1 elements. parents may contain 0, 1, or multiple elements.
The code can be written as follows:
$ ('# Dwtedx '). parents ('. par'); // you can find that all classes are. par node $ ('# dwtedx '). closest ('. par '); // you can find a parent node, which is the one on the previous layer.
Get JQUERY sibling Node
Get the jQuery sibling node. Our idea is to find the parent node through the current node, and then find the child node through the parent node. The Code is as follows:
$ (". Title "). parent (). find ('ul '); // find your brother node ul is to first find the parent node li of h3 and ul, and then use find () to find ul
Another method is to use the siblings () function and the code is as follows:
$ (". Title"). siblings ('ul '); // find your brother node ul
Obtain JQUERY subnodes
Match the first child element: first matches only one element, and this selector matches one child element for each parent element.
$ (". Par: first-child"); // get the node whose id is firstli
The Code is as follows:
$ ('# Firstli h3.title'); // obtain h3 of Entry 1
Use the find () function. As mentioned above, the usage is the same.
$ ("# Firstli"). find ("h3"); // find the child sibling node h3
Use the children () function and the code is as follows:
$ ("# Firstli"). children ("h3.title"); // obtain the child node h3 and class as title