如何使用JavaScript为所有td元素添加统一的class类
报错原因
document.querySelectorAll() 返回的是包含所有匹配元素的 NodeList类数组对象,不是单个DOM元素,只有单个DOM元素才具备setAttribute方法,直接对集合调用该方法会抛出类型错误。
解决方法
方法1:遍历NodeList逐个添加class(兼容性好,推荐使用)
const allTd = document.querySelectorAll('td'); allTd.forEach(td => { // 方式一:直接替换整个class属性 td.setAttribute('class', 'tds'); // 方式二:追加class,不会覆盖元素已有的其他class,更灵活 // td.classList.add('tds'); });
如果需要兼容IE11及更早版本(不支持NodeList的forEach方法),可以使用传统for循环:
const allTd = document.querySelectorAll('td'); for(let i = 0; i < allTd.length; i++) { allTd[i].classList.add('tds'); }
方法2:转为数组后操作(适合需要额外数组处理的场景)
const allTdArr = Array.from(document.querySelectorAll('td')); allTdArr.forEach(td => td.classList.add('tds'));
内容的提问来源于stack exchange,提问作者M P
相关产品推荐
相关产品推荐

