登录
首页 >  文章 >  前端

getAttribute和setAttribute使用详解

时间:2026-04-21 19:45:49 107浏览 收藏

本文深入解析了 getAttribute 和 setAttribute 的核心使用场景与关键陷阱,强调必须严格区分 HTML 属性(静态声明、字符串化)与 DOM 属性(动态状态、原生类型),并指出对 value、checked、class、style、data-* 等常见属性,直接操作 DOM 属性或使用 classList/dataset/style.cssText 等现代 API 才更准确、高效、安全;掌握这些差异,能帮你避开运行时状态不同步、样式被意外覆盖、布尔属性误判等高频坑,写出更健壮、可维护的 DOM 操作代码。

如何用 getAttribute 与 setAttribute 动态修改元素属性

getAttributesetAttribute 修改元素属性,关键在于区分“HTML 属性”和“DOM 属性”,并确保操作的是真实存在的元素节点。

获取属性值:getAttribute 的正确用法

getAttribute() 读取的是元素在 HTML 中显式声明的属性(包括自定义属性),不反映运行时动态变化的 DOM 状态(比如 input.value 的当前输入内容)。

  • 对标准属性(如 idclasssrc)有效,但注意:class 获取的是字符串,不是类名数组
  • 对布尔属性(如 disabledchecked)返回 "disabled"null(未设置时),不是 true/false
  • 支持获取自定义属性(如 data-iddata-user-name),推荐用 dataset 更方便

示例:

const btn = document.querySelector('button');
console.log(btn.getAttribute('disabled')); // "disabled" 或 null
console.log(btn.getAttribute('data-count')); // "5"

设置属性值:setAttribute 的注意事项

setAttribute() 会把值转为字符串写入 HTML 属性,适用于初始化或覆盖式修改;但它不等同于直接赋值 DOM 属性(如 elem.value = 'xxx')。

  • 设置 class 会完全替换原有 class 字符串,建议用 classNameclassList 更安全
  • 设置 style 会覆盖整个内联样式,应优先使用 elem.style.xxx = 'value'
  • 设置布尔属性(如 disabled)只需传任意非空字符串(如 "disabled"""),移除则用 removeAttribute()

示例:

const img = document.querySelector('img');
img.setAttribute('src', '/new.jpg');
img.setAttribute('data-loaded', 'true');
img.setAttribute('disabled', ''); // 等效于设为禁用

什么时候不该用 get/setAttribute

以下情况推荐直接操作 DOM 属性或使用专用 API,更准确、高效:

  • valuecheckedselecteddisabled 等表单/状态属性 → 直接读写 elem.valueelem.checked
  • className → 用 elem.classNameelem.classList.add/remove/toggle
  • style → 用 elem.style.color = 'red'elem.style.cssText
  • data-* 属性 → 用 elem.dataset.xxx(自动驼峰转换,如 data-user-iddataset.userId

实用小技巧:结合使用提升可维护性

动态修改常配合条件判断与事件处理,注意避免重复设置或无效操作:

  • 设置前先检查是否已存在目标属性,减少无谓重绘(尤其对 styleclass
  • 批量更新多个属性时,考虑用 Object.assign(elem, { value: 'x', disabled: true })(仅限可写 DOM 属性)
  • 监听属性变化可用 MutationObserver,但仅监控 attributes: true 时才捕获 setAttribute 触发的变更

今天关于《getAttribute和setAttribute使用详解》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>