jQuery :first-of-type 选择器
实例
选择作为属于其父元素的第一个 <p> 元素的所有 <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-of-type").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-of-type 选择器选择作为其父元素的第一个子元素(特定类型)的所有元素。
提示: 这个选择器与 :nth-of-type(1) 类似。
提示:使用 :last-of-type 选择器选择属于父元素的特定类型的最后一个子元素。
语法
$(":first-of-type")
更多实例
如何选择所有 <div> 元素中的第一个 <p> 元素。
:first-child 与 :first-of-type 选择器的不同点
演示 :first-child 与 :first-of-type 选择器的不同点