特性和属性的区别

当写 HTML 源代码时,你可以在 HTML 元素上定义特性attribute。一旦浏览器解析了你的代码,将产生一个对应的 DOM 节点。这个节点是个对象,因而它具有属性property

例如,如下 HTML 元素:

<input type="text" value="Name:">
1

有两个特性atrribute

一旦浏览器解析这段代码,将产生一个HTMLInputElement对象,并且这个对象将包含几十个属性property,比如:acceptaccessKeyalignaltattributesautofocusbaseURIcheckedchildElementCountchildNodeschildrenclassListclassNameclientHeight等等。

对于 DOM 节点对象来说,属性property是节点对象的属性property,特性attribute是节点对象的attributes属性的元素。 (For a given DOM node object, properties are the properties of that object, and attributes are the elements of the attributes property of that object.)

对于给定的 HTML 元素,其 DOM 节点创建时,它的许多属性property以相同或者相似的名字与特性attribute相关联,但不是一一对应的关系。例如,对于以下的 HTML 元素:

<input id="the-input" type="text" value="Name">
1

与之对应的 DOM 节点会有idtypevalue属性:

  • id属性映射到id特性:获取属性property时将读取特性attribute的值,设置属性property时将重写特性attribute的值。id是纯映射属性,它不会修改或者限制值。
  • type属性映射到type特性:获取属性property时将读取特性attribute的值,设置属性property时将重写特性attribute的值。type不是纯映射属性,因为它的取值限制于已知的值(即input元素type的有效值)。如果有<input type="foo">,则theInput.getAttribute("type")会得到foo,但是theInput.type会得到text
  • 相反的,value属性不会映射到value特性。取而代之的是value属性将获得input的当前值。当用户手动的改变input输入框的value值,value属性将反映出这个改变。因此如果用户输入 'John',则:
theInput.value // returns "John"
1

theInput.getAttribute("value") // returns "Name"
1

value属性反映出input输入框的当前text-content,而value特性包含了input输入框value特性的初始text-content

因此如果你想要知道文本输入框的当前值,读取属性property。如果你想要知道文本输入框的初始值,读取特性attribute。或者你可以使用defaultValue属性,这是一个value特性的映射属性。

theInput.value                 // returns "John"
theInput.getAttribute("value") // returns "Name"
theInput.defaultValue          // returns "Name"
1
2
3

有好几个属性是直接映射到它们对应的特性attribute上的,比如relid。一些属性也是直接映射的,但是名字稍有不同,比如htmlFor属性映射到for特性,className映射到class特性。还有许多属性映射到它们对应的特性,但是有限制和修改,比如srchrefdisabledmultiple等等。这份文档open in new window包含了各种各样的映射。

翻译自:http://stackoverflow.com/questions/6003819/properties-and-attributes-in-html#answer-6004028open in new window

结论

HTML attributeDOM property
值永远是字符串或null值可以是任意合法js类型
大小写不敏感大小写敏感
不存在时返回null不存在时返回undefined
对于href,返回html设置的值对于href返回解析后的完整url
更新value,属性也更新更新value,特性不更新

详情请见: HTML attribute 和 DOM propertyopen in new window