使用setAttribute()可设置元素属性,如class和data-id;通过getAttribute()获取属性值,removeAttribute()删除属性,布尔属性可用点语法控制,优先使用classList和语义化方法优化代码。

在JavaScript中设置和修改HTML属性是前端开发中的基础操作。通过JS可以动态控制元素的外观、行为以及语义,提升页面交互性。下面详细介绍常用方法及实际应用场景。
使用setAttribute()方法
setAttribute() 是最常用的方法之一,用于设置或修改指定元素的属性值。
语法:element.setAttribute('attributeName', 'value');
示例:假设有一个按钮:
立即学习“前端免费学习笔记(深入)”;
用JS添加class和data-id:
const btn = document.getElementById('myBtn');
btn.setAttribute('class', 'btn-primary');
btn.setAttribute('data-id', '123');
执行后,按钮的HTML变为:
使用getAttribute()获取属性值
配合 setAttribute 使用,可通过 getAttribute() 获取当前属性值。
const id = btn.getAttribute('data-id'); // 返回 "123"
这个方法常用于判断或读取自定义属性(如 data-*)进行逻辑处理。
直接操作元素的属性(点语法)
部分HTML属性对应DOM元素的JS属性,可直接通过点语法访问和修改。
- src、href、id、className、style 等都可以这样操作
例如:
const img = document.querySelector('img');
img.src = 'new-image.jpg';
img.className = 'rounded';
注意:HTML中的 class 属性在JS中对应的是 className(因为class是保留字)。
移除属性用removeAttribute()
若要删除某个属性,使用 removeAttribute()。
btn.removeAttribute('data-id');
执行后,data-id 属性将从元素中完全移除。
特殊属性:布尔型属性的处理
像 disabled、checked、readonly 这类布尔属性,其存在即表示“真”。
正确做法是:
document.getElementById('myInput').disabled = true; // 禁用输入框
document.getElementById('myInput').disabled = false; // 启用
也可以用 setAttribute 和 removeAttribute:
- 设置:element.setAttribute('disabled', '')
- 移除:element.removeAttribute('disabled')
仅添加属性名(值为空字符串)即可生效,这是HTML标准允许的。
注意事项与最佳实践
- 优先使用语义化方法:比如修改class时推荐使用 classList.add()/remove() 而非直接设置className
- 避免频繁操作DOM属性,可先缓存元素引用
- 自定义属性建议使用 data-* 格式,便于管理且符合规范
- 某些属性如 style、onclick 等应尽量通过CSS类或事件监听器代替内联设置
基本上就这些。掌握 setAttribute、getAttribute、removeAttribute 和直接属性赋值,就能灵活控制HTML元素的各种特性。根据场景选择合适方式,代码会更清晰高效。











