如何通过属性名获取DOM元素并为其设置新属性?
解决方法:为带自定义属性的a标签添加class
先纠正核心错误
你之前的代码没生效,主要是两个问题:
- 选择器不匹配:DOM里的属性是
myOwnAttributeName,但你写的选择器是a[myOwnAttribute="#hello"],不仅属性名写错,还多了不必要的#符号,根本没选中目标元素。 - 操作对象错误:
querySelectorAll返回的是元素集合(NodeList),不能直接对集合调用setAttribute,得遍历每个元素或者取单个元素操作。
正确代码示例
HTML结构
<html> <a href="#" myOwnAttributeName="hello">Click me</a> </html>
JavaScript代码
方式1:针对单个元素(推荐用querySelector)
// 用正确选择器选中单个元素 const targetLink = document.querySelector('a[myOwnAttributeName="hello"]'); if (targetLink) { // 方法A:用setAttribute设置class(会覆盖原有class) targetLink.setAttribute('class', 'class-hello'); // 方法B:用classList添加class(更灵活,不会覆盖原有class,还能批量添加) // targetLink.classList.add('class-hello'); }
方式2:针对多个元素(用querySelectorAll遍历)
// 选中所有符合条件的元素 const targetLinks = document.querySelectorAll('a[myOwnAttributeName="hello"]'); // 遍历集合,给每个元素添加class targetLinks.forEach(link => { link.classList.add('class-hello'); });
最终效果
执行代码后,DOM会变成:
<a href="#" myOwnAttributeName="hello" class="class-hello">Click me</a>
内容的提问来源于stack exchange,提问作者Sanjay
相关产品推荐
相关产品推荐

