You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

jQuery中使用:last-child选择器无法选中最后一个p元素问题咨询

问题根因
  • :last-child是标准CSS选择器,匹配规则为:元素必须是其父节点的最后一个直接子节点,不限制节点类型,只要位置是最后一个即可。你提供的代码中<body>的最后一个子节点是<script>标签,不是<p>标签,因此p:last-child无法匹配到任何元素。
  • :first-child可以正常匹配,是因为<body>的第一个子节点确实是<p>标签,符合匹配规则。
  • jQuery自定义的:last选择器规则为:从所有匹配到的目标元素集合中取最后一个,不要求该元素是父节点的最后一个子节点,因此可以正常生效。
解决方案

如果你要使用:last-child完成匹配,可选用以下任意一种方案:

  1. 调整DOM结构
    确保<body>的最后一个子节点是<p>元素,将业务代码的<script>标签移到<head>内,同时用$(document).ready()保证DOM加载完成后再执行选择逻辑,代码示例如下:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script>
        document.title = "Selectors";
        $(document).ready(function(){
            $("p:first-child").html("First child of Body");
            $("p:last-child").html("Last child of Body");     
        })
    </script>
</head>
<body>
    <p>Paragraph 1</p>
    <p class="p2" >Paragraph 2</p>
    <p id="p3">Paragraph 3</p>
</body>
</html>
  1. 替换为同类型匹配选择器
    如果不想调整DOM结构,可使用:last-of-type选择器替代,它的规则为匹配父节点下同类型元素的最后一个,不需要满足是父节点最后一个子节点的要求,只需修改选择器代码即可:
$("p:last-of-type").html("Last child of Body");

内容的提问来源于stack exchange,提问作者Yağız Esmerligil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 05:15:03