在HTML和DOM中,"特性"(attributes)和"属性"(properties)是两个相关但不同的概念,初学者经常容易混淆它们。
<input id="username" type="text" value="John">
中的 id
、type
和 value
都是特性element.getAttribute(name)
- 获取特性值element.setAttribute(name, value)
- 设置特性值element.hasAttribute(name)
- 检查是否存在特性element.removeAttribute(name)
- 删除特性document.getElementById('username').value
访问的是属性类型不同:
命名差异:
同步行为:
<input id="age" type="number" value="30" disabled custom-attr="hello">
const input = document.getElementById('age');
// 特性访问
console.log(input.getAttribute('value')); // "30" (字符串)
console.log(input.getAttribute('disabled')); // "" (空字符串表示存在)
console.log(input.getAttribute('custom-attr')); // "hello"
// 属性访问
console.log(input.value); // 30 (数字)
console.log(input.disabled); // true (布尔值)
console.log(input.customAttr); // undefined (非标准特性不作为属性存在)
// 修改属性会影响特性(对于标准属性)
input.value = 35;
console.log(input.getAttribute('value')); // "35" (同步更新)
// 但修改特性不总是影响属性
input.setAttribute('value', '40');
console.log(input.value); // 35 (未改变,因为用户可能已经修改过)
data-*
特性,可以通过 dataset
属性访问disabled
, checked
等,在HTML中只要存在就为true(无论值是什么),但在DOM属性中是布尔值类名:
class
(字符串)className
(历史原因) 和 classList
(现代API)样式:
style
(字符串,如 "color: red; font-size: 16px;")style
(CSSStyleDeclaration对象)理解特性和属性的区别对于有效操作DOM非常重要,特别是在处理表单元素、自定义数据和动态内容时。