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

如何使用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 11:45:04