jQuery traversal children() method

jQuery is a collection object. If you want to quickly find the first-level child elements in the collection, you can use the children() method.

Note here: The .children(selector) method returns all child elements of each element in the matching element set (only the son generation, which can be understood as the father-son relationship)

Understand the node search relationship:

##                                                                                                                   + div and ul have a parent-child relationship, and li and div have an ancestor relationship, so they cannot be found.


children() has no parameters

Allows us to search the direct child elements of these elements in the DOM tree and construct a new jQuery object of the matching element

Note: jQuery is a collection object, so children is the first-level child element that matches each given element in the collection.

The children() method selectively accepts the same type of selector expression

$("div").children(".selected")

Similarly because jQuery is a collection object, you may need to filter this collection object to find the target element, so Allows passing a selector expression

Let’s write an example below:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>childred()</title>
    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script>
</head>
<body>
    <div>
        <ul>
            <li>php.cn</li>
            <li>php 中文网</li>
        </ul>

        <p>  php </p>
    </div>


    <script>
        $("div").children().css("color", "red");
    </script>
</body>
</html>

As shown in the above code, when we write $("div").children().css("color ", "red"); He will look for the child elements below the div, so the elements in the div will turn red. Let's look at another

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>childred()</title>
    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script>
</head>
<body>
    <div>
        <ul>
            <li>php.cn</li>
            <li>php 中文网</li>
        </ul>

        <p>  php </p>
    </div>


    <script>
        $("div").children(':first').css("color", "red");
    </script>
</body>
</html>

code above, we will see p The color of the elements within the tag has not changed, because we have a parameter in children(), first is the first one, so we will look for the first child element in the div

As you can see<ul> It is the first element of our div, so the elements within the li tag will change. You can try writing a piece of code locally

Continuing Learning
||
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>childred()</title> <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script> </head> <body> <div> <ul> <li>php.cn</li> <li>php 中文网</li> </ul> <p> php </p> </div> <script> $("div").children().css("color", "red"); </script> </body> </html>
submitReset Code