如何通过单个事件监听器修改多个DOM元素的样式
问题原因
document.querySelectorAll(".heading-title") 返回值是匹配所有对应选择器的DOM元素组成的NodeList集合,不是单个DOM元素,集合本身不存在style属性,因此直接对集合赋值style.color不会产生效果。
单个元素修改能正常运行,是因为document.querySelector()仅返回匹配到的第一个DOM元素,属于单个DOM对象,可直接设置style属性。
实现方案
方案1:直接遍历修改内联样式
遍历获取到的NodeList集合,为每个标题元素单独设置颜色属性即可,现代浏览器可直接调用NodeList的forEach方法遍历:
const customColor1Btn = document.querySelector(".custom-color-1"); const headings = document.querySelectorAll(".heading-title"); customColor1Btn.addEventListener("click", function () { headings.forEach(heading => { heading.style.color = "red"; }); });
如果需要兼容不支持NodeList原生forEach方法的老旧浏览器,可以先将NodeList转为数组再遍历:
customColor1Btn.addEventListener("click", function () { Array.from(headings).forEach(heading => { heading.style.color = "red"; }); });
方案2:批量切换CSS类(推荐)
如果后续需要批量修改的样式不止颜色一种,更推荐提前定义好对应样式的CSS类,点击时统一为元素添加类名,后续维护修改更方便:
/* 提前在CSS文件中定义样式类 */ .heading-red { color: red; }
const customColor1Btn = document.querySelector(".custom-color-1"); const headings = document.querySelectorAll(".heading-title"); customColor1Btn.addEventListener("click", function () { headings.forEach(heading => { heading.classList.add("heading-red"); }); });
内容的提问来源于stack exchange,提问作者ChristosDg
相关产品推荐
相关产品推荐

