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

如何给所有类名以example开头的div元素添加class?(非jQuery)

解决方法:给所有类名以"example"开头的div添加class(无jQuery)

我来帮你搞定这个问题!你的代码有几个关键问题导致没效果,先帮你梳理清楚:

  • document.querySelector('div')只会选中页面上第一个div元素,没法处理所有符合条件的div
  • 你把获取到的类名字符串存在了divClass变量里,之后直接操作这个字符串的classList——但字符串根本没有classList属性,这会直接报错
  • 就算前面的问题都解决,divClass.startsWith('example')只能匹配第一个类名就是example的情况,如果div的类是other-class example-box,这个判断就会失效

下面给你两种靠谱的实现方式,选哪种都可以:

方法1:遍历所有div,检查类列表

这种方法更灵活,适合需要自定义判断逻辑的场景:

// 获取页面上所有div元素
const allDivs = document.querySelectorAll('div');

// 逐个遍历处理
allDivs.forEach(div => {
  // 把类列表转成数组,检查是否有类名以"example"开头
  const hasTargetClass = Array.from(div.classList).some(className => className.startsWith('example'));
  
  if (hasTargetClass) {
    // 给符合条件的div添加新class
    div.classList.add('width', 'height');
  }
});

方法2:用CSS选择器直接定位目标div(更简洁高效)

利用CSS属性选择器,直接选中所有类名以"example"开头的div(包括类列表中任意位置的情况):

// 匹配两种情况:类名以example开头,或者类名中包含"空格+example"(即第二个及以后的类是example开头)
const targetDivs = document.querySelectorAll('div[class^="example"], div[class*=" example"]');

// 给每个匹配的div添加class
targetDivs.forEach(div => {
  div.classList.add('width', 'height');
});

补充说明

  • class^="example":匹配类名开头就是example的元素
  • class*=" example":匹配类列表中包含空格+example的元素(处理类名不在第一个位置的情况)
  • 两种选择器组合起来,就能覆盖所有类名以example开头的场景啦

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:26:04