jQuery find() 方法查找给定选择器的后代元素。后代可以是孩子、孙子等。它是 jQuery 中的内置方法。为了查找后代,find() 方法从 DOM 树中的选定元素向下遍历。
我们可以使用 "*" 选择器来返回所有后代元素。要返回给定选择器的所有后代元素,我们必须这样写。
$(selector).find("*")
children() 方法的工作原理类似于 find() 方法。与 find() 方法不同,children() 方法沿 DOM 树向下遍历一层,即返回直接子级。语法
$(selector).find(filter)
filter: 该值可以是选择器表达式、元素或 jQuery 对象。例子
<!DOCTYPE html>
<html>
<head>
<style>
.main * {
display: block;
font-size: 20px;
position: relative;
border: 2px solid black;
color: black;
padding: 10px;
margin: 17px;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
function fun(){
$(document).ready(function(){
$("#div1").find("ul").css({ "font-size": "30px", "color": "blue", "border": "6px dashed blue"});
});
}
</script>
</head>
<body class = "main"> body
<div id = "div1"> div1
<div> div2
<ul> ul
<h2> h2
<ul> ul
<p> p元素 </p>
</ul>
</h2>
</ul>
</div>
</div>
<button onclick = "fun()"> 点击看看 </button>
</body>
</html>
例2
<!DOCTYPE html>
<html>
<head>
<style>
.main * {
display: block;
font-size: 20px;
position: relative;
border: 2px solid black;
color: black;
padding: 10px;
margin: 17px;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
function fun(){
$(document).ready(function(){
$("#div1").find("div,ul,p").css({"color": "blue", "border": "6px dashed blue"});
});
}
</script>
</head>
<body class = "main"> body
<div id = "div1"> div1
<div> div2
<ul> ul
<h2> h2
<ul> ul
<p> p元素 </p>
</ul>
</h2>
</ul>
</div>
</div>
<button onclick = "fun()"> 点击看看 </button>
</body>
</html>
例3
<!DOCTYPE html>
<html>
<head>
<style>
.main * {
display: block;
font-size: 20px;
position: relative;
border: 2px solid black;
color: black;
padding: 10px;
margin: 17px;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
function fun(){
$(document).ready(function(){
$("#div1").find("*").css({"color": "blue", "border": "6px dashed blue"});
});
}
</script>
</head>
<body class = "main"> body
<div id = "div1"> div1
<div> div2
<h2> h2
<p> p元素 </p>
</h2>
</div>
</div>
<button onclick = "fun()"> click me </button>
</body>
</html>