jquery查找子元素
jQuery 查找子元素的方法
在 jQuery 中,可以通过多种方式查找子元素。以下是几种常用的方法:
使用 children() 方法
children() 方法返回被选元素的所有直接子元素(仅一层深度)。可以传入选择器进一步过滤结果。
$("#parent").children(); // 获取所有直接子元素
$("#parent").children(".child-class"); // 获取特定类名的直接子元素
使用 find() 方法
find() 方法返回被选元素的所有后代元素(包括多层嵌套)。通常用于查找深层嵌套的子元素。
$("#parent").find(".target"); // 查找所有符合选择器的后代元素
使用 > 子选择器
在 jQuery 选择器中,> 符号用于匹配直接子元素。
$("#parent > .child"); // 选择直接子元素中类名为 child 的元素
使用 :first-child 或 :last-child 伪类
这些伪类选择器可以匹配特定位置的子元素。
$("#parent li:first-child"); // 选择第一个子元素
$("#parent li:last-child"); // 选择最后一个子元素
使用 eq() 方法
通过索引选择特定位置的子元素。
$("#parent").children().eq(0); // 选择第一个子元素(索引从 0 开始)
示例代码
以下是一个完整的示例,展示如何查找子元素:

<div id="parent">
<div class="child">Child 1</div>
<div class="child">Child 2</div>
<div class="nested">
<div class="grandchild">Grandchild</div>
</div>
</div>
<script>
// 获取所有直接子元素
$("#parent").children().css("color", "red");
// 查找嵌套的子元素
$("#parent").find(".grandchild").css("font-weight", "bold");
// 使用子选择器
$("#parent > .child:first-child").text("First child modified");
</script>
注意事项
children()仅查找直接子元素,而find()会遍历所有后代。- 子选择器(
>)在性能上通常优于find(),因为它只匹配一层。 - 伪类选择器如
:first-child是基于 DOM 结构而非 jQuery 对象的位置。






