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
相关产品推荐
相关产品推荐

