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

querySelector仅选中单个div,如何选中所有拥有相同类名的div?

解决方案

document.querySelector 仅会返回匹配选择器的第一个元素,要获取所有符合条件的元素,需要改用 document.querySelectorAll 方法,再遍历返回的NodeList集合对每个元素执行操作即可。

修改后的代码如下:

// 获取所有带test类的元素
const removeCurveStrokeList = document.querySelectorAll('.test');

// 遍历所有匹配元素执行类名替换逻辑
removeCurveStrokeList.forEach(item => {
  if(item.classList.contains('card-decorator-stroke')){
    item.classList.remove("card-decorator-stroke");
    item.classList.add("brand-curve-stroke");
  }
})

如果需要兼容不支持 NodeList.prototype.forEach 的旧版本浏览器,可以改用for循环实现遍历:

var removeCurveStrokeList = document.querySelectorAll('.test');
var i;
for (i = 0; i < removeCurveStrokeList.length; i++) {
  var currentItem = removeCurveStrokeList[i];
  if(currentItem.classList.contains('card-decorator-stroke')){
    currentItem.classList.remove("card-decorator-stroke");
    currentItem.classList.add("brand-curve-stroke");
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 01:36:02