jquery 子元素筛选选择器

复制代码
<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <title></title>
    <link rel="stylesheet" href="imooc.css" type="text/css">
    <script src="https://www.imooc.com/static/lib/jquery/1.9.1/jquery.js"></script>
</head>

<body>
    <h2>子元素筛选选择器</h2>
    <h3>:first-child、:last-child、:only-child</h3>
    <div class="left first-div">
        <div class="div">
            <a>:first-child</a>
            <a>第二个元素</a>
            <a>:last-child</a>
        </div>
        <div class="div">
            <a>:first-child</a>
        </div>
        <div class="div">
            <a>:first-child</a>
            <a>第二个元素</a>
            <a>:last-child</a>
        </div>
    </div>

    <script type="text/javascript">
        //查找class="first-div"下的第一个a元素
        //针对所有父级下的第一个
        $('.first-div a:first-child').css("color", "#CD00CD");
    </script>

    <script type="text/javascript">
        //查找class="first-div"下的最后一个a元素
        //针对所有父级下的最后一个
        //如果只有一个元素的话,last也是第一个元素
        $('.first-div a:last-child').css("color", "red");
    </script>

    <script type="text/javascript">
        //查找class="first-div"下的只有一个子元素的a元素
        $('.first-div a:only-child').css("color", "blue");
    </script>


    <h3>:nth-child、:nth-last-child</h3>
    <div class="left last-div">
        <div class="div">
            <a>:first-child</a>
            <a>第二个元素</a>
            <a>第三个元素</a>
            <a>:last-child</a>
        </div>
        <div class="div">
            <a>:first-child</a>
            <a>第二个元素</a>
        </div>
        <div class="div">
            <a>:first-child</a>
            <a>第二个元素</a>
            <a>第三个元素</a>
            <a>:last-child</a>
        </div>
    </div>

    <script type="text/javascript">
        //查找class="last-div"下的第二个a元素
        $('.last-div a:nth-child(2)').css("color", "#CD00CD");
    </script>

    <script type="text/javascript">
        //查找class="last-div"下的倒数第二个a元素
        $('.last-div a:nth-last-child(2)').css("color", "red");
    </script>

</body>

</html>
复制代码

 

posted @   wzndkj  阅读(10535)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示