jQuery :first-child 选择器
实例
选择作为其父元素的第一个子元素的所有 <p> 元素:
<!DOCTYPE html><html><head><script src="https://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script><script>$(document).ready(function(){$("p:first-child").css("background-color", "yellow");});</script></head><body><p>body 中的第一个段落</p><div style="border:1px solid;"><p>div 中的第一个段落</p><p>div 中的最后一个段落</p></div><div style="border:1px solid;"><span>这是一个 span 元素.</span><p>另一个 div 中的第一个段落</p><p>另一个 div 中的最后一个段落</p></div><p>body 中的最后一个段落</p></body></html>
定义与用法
:first-child 选择器选择作为其父元素的第一个子元素的所有元素。
提示: 使用 :last-child 选择器选择作为其父元素的最后一个子元素的所有元素。
语法
$(":first-child")
更多实例
如何选择选择所有 <div> 元素中的第一个 <p> 元素
演示 :first 与 :first-child 选择器的不同点
:first-child 与 :first-of-type 选择器的不同点
演示 :first-child 与 :first-of-type 选择器的不同点