700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > jQuery 查找后代元素

jQuery 查找后代元素

时间:2021-02-15 19:00:28

相关推荐

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"));

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。