jQuery 查找后代元素

通过jQuery children() 方法和jQuery find() 方法,我们可以向下遍历 DOM 树,查找后代元素。

(1) jQuery children() 方法:返回被选元素的所有直接子元素。

(2)jQuery find() 方法:返回被选元素的后代元素。

值得一提的是,我们可以对后代元素进行筛选。

示例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
       .great-grandson {
           width: 50px;
           height: 50px;
           background-color: blueviolet;
       }
       .grandson {
           width: 100px;
           height: 100px;
           background-color: cornflowerblue;
       }
       .son {
           width: 150px;
           height: 150px;
           background-color: crimson;
       }
       .father {
           width: 200px;
           height: 200px;
           background-color: rgba(30, 201, 39, 0.767);
       }
       p {
           margin: 0;
       }
    </style>
    <script src="jQuery.min.js"></script>
    <script>
        $(document).ready(function(){
            console.log($(".father").children());
            console.log($(".father").children("p"));
            console.log($(".father").find("*"));
            console.log($(".father").find("div,li"));
        })
    </script>
</head>
<body>
    <div class="father">自己
        <div class="son">儿子
            <ul class="grandson">孙子
                <li class="great-grandson">重孙子</li>
            </ul>
        </div>
        <p>我是另一个直接子元素</p>
    </div>
</body>
</html>

控制台输出:

(1)输出所有所有直接子元素:

            console.log($(".father").children());

(2)对直接子元素进行筛选:

            console.log($(".father").children("p"));

(3)输出所有后代元素:

            console.log($(".father").find("*"));

(4)输出后代元素进行筛选:

            console.log($(".father").find("div,li"));

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值