理解Jquery的first-of-type选择器

来源:互联网 发布:高校教学软件租赁 编辑:程序博客网 时间:2024/05/19 18:15

理解Jquery的first-of-type选择器

$(“p:first-of-type”)

选取属于其父元素的第一个 p 元素的每个p元素:

实例代码

<!DOCTYPE html><html>    <head>        <meta charset="utf-8">        <title>first-child选择器</title>        <script src="../../jquery.min.js">        </script>        <script>            $(document).ready(function(){                $("p:first-of-type").css("background-color","red");            });        </script>    </head>    <body>        <p>the first paragraph in body</p>        <div style="border:1px solid;">            <p>The first paragraph in div.</p>            <p>the last paragraph in div.</p>        </div><br>        <div style="border:1px solid;">            <span>This is a span element.</span>            <p>The first paragraph in another div.</p>            <p>The last paragraph in another div.</p>        </div>    </body></html>

dom树

dom树结构

通俗解释

首先定位到当前文档中的所有p元素的父级元素,然后在每个父级元素下,找到第一个为p类型的元素,然后再给其加上背影效果,特别要区分开(p:firstchild)(“p:last-of-type”),刚好和此相反。

扩展

$(“p:nth-of-type(n)”)
属于其父元素的第n个 p 元素的所有 p 元素

$(“p:nth-last-of-type(n)”)
选取属于其父元素的第三个 p 元素的每个 p 元素,从最后一个子元素开始计数

0 0