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

动态DOM场景下如何用CSS选取最后一个带accomplished类的子元素

解决方法:选取最后一个带.accomplished类的子元素

针对你这种动态生成的DOM结构,我推荐两种可行的方案,分别用纯CSS和JS实现,你可以根据浏览器兼容性需求来选:

方案一:使用CSS :has() 选择器(现代浏览器推荐)

现在主流浏览器已经支持:has()伪类了,它能帮我们精准定位到最后一个包含.child.accomplished的父块,再选中里面的目标子元素。代码如下:

/* 选中最后一个包含.child.accomplished的parent-block里的该子元素 */
.parent-block:has(.child.accomplished):not(:has(~ .parent-block:has(.child.accomplished))) .child.accomplished {
  /* 这里写你要的样式,比如 */
  background-color: #e6f7ff;
  border-left: 3px solid #1890ff;
}

选择器拆解:

  • .parent-block:has(.child.accomplished):先筛选出所有包含.child.accomplished子元素的父块
  • :not(:has(~ .parent-block:has(.child.accomplished))):排除掉后面还有其他同类父块的元素(~是兄弟选择器,代表当前元素之后的同级元素)
  • 最后加上.child.accomplished,就精准定位到了最后一个符合条件的子元素

方案二:JavaScript 实现(兼容旧浏览器)

如果需要兼容不支持:has()的旧浏览器,用JS来实现会更稳妥,而且动态生成元素后也能方便地重新执行逻辑:

// 获取所有带.accomplished类的子元素
const accomplishedChildren = document.querySelectorAll('.child.accomplished');

// 如果存在这样的元素,选中最后一个并应用样式
if (accomplishedChildren.length > 0) {
  const lastAccomplished = accomplishedChildren[accomplishedChildren.length - 1];
  // 直接加样式
  lastAccomplished.style.cssText = `
    background-color: #e6f7ff;
    border-left: 3px solid #1890ff;
  `;
  // 或者给它加一个自定义类,后续在CSS里写样式(更推荐,样式和逻辑分离)
  // lastAccomplished.classList.add('last-accomplished-item');
}

动态元素适配:

如果你的DOM是动态加载的(比如异步请求后生成),可以把这段代码放在元素生成完成后执行,或者用MutationObserver监听DOM变化,自动触发样式应用逻辑。

内容的提问来源于stack exchange,提问作者Oleksii

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 18:07:53