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

如何查找类名包含指定子串的DOM元素?(含wrapper示例)

查找包含指定子串类名的DOM元素

方法1:原生JS querySelector(最简便)

利用CSS属性包含选择器,直接匹配class属性中带有wrapper子串的元素,代码如下:

const targetElement = document.querySelector('[class*="wrapper"]');

因为你明确文档中只有一个符合条件的元素,这个方法会直接返回目标元素。

如果目标类名总是以wrapper结尾(比如示例中的wp-rgtayfu-fxyjzw-wrapper),可以用更精准的结尾匹配选择器,避免误匹配其他带wrapper的字符串:

const targetElement = document.querySelector('[class$="wrapper"]');

方法2:手动遍历筛选

如果需要自定义判断逻辑,可以遍历所有元素并检查类名:

let targetElement;
const allElements = document.querySelectorAll('*');
for (const elem of allElements) {
  if (elem.className.includes('wrapper')) {
    targetElement = elem;
    break; // 找到即停止,符合唯一元素的条件
  }
}

补充:CSS中直接选中元素

如果是在样式表中要选中该元素,同样使用对应的属性选择器:

[class*="wrapper"] {
  /* 你的样式 */
}

或者精准结尾匹配:

[class$="wrapper"] {
  /* 你的样式 */
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 05:45:32