如何使用JavaScript修改多个带有相同class的a元素的href属性
问题原因
document.querySelector()设计为仅返回第一个匹配到的DOM元素,所以只会修改第一个符合条件的链接。document.querySelectorAll()返回的是包含所有匹配元素的NodeList类数组对象,并非单个DOM节点。直接给这个集合设置.href属性,是给集合对象本身新增自定义属性,不会作用到集合内的每一个DOM元素上,因此没有效果。
解决方法
你需要遍历querySelectorAll返回的NodeList,逐个修改每个元素的href属性,以下是两种常用实现方案:
方案1:forEach遍历(现代浏览器适用)
const googleLinks = document.querySelectorAll('a.google'); googleLinks.forEach(link => { link.href = 'https://google.com'; });
方案2:for循环遍历(兼容所有旧版浏览器)
如果需要兼容不支持NodeList.forEach的旧浏览器,可以使用普通for循环实现:
const googleLinks = document.querySelectorAll('a.google'); for (let i = 0; i < googleLinks.length; i++) { googleLinks[i].href = 'https://google.com'; }
内容的提问来源于stack exchange,提问作者qwyzex
相关产品推荐
相关产品推荐

