detail-attributes和properties的区别

背景

看到一个很有意思的讨论what-is-the-difference-between-properties-and-attributes-in-html觉得有必要记录一下

说明

English 定义:

  • Attributes are referring to additional information of an object.(Attributes指的是对象的附加信息)
  • Properties are describing the characteristics of an object.(Properties描述了对象的特征)

编写HTML源代码时,可以在HTML元素上定义Attributes。
然后,一旦浏览器解析您的代码,将创建相应的DOM节点。
此节点是一个对象,因此它具有Properties。

举例说明:

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

这个例子有俩个Attributes (type和value)。
浏览器解析此代码后,将创建一个HTMLInputElement对象,该对象将包含许多属性,如:accept,accessKey,align,alt,attributes,autofocus,baseURI,checked,childElementCount,childNodes,children,classList,className,
clientHeight等。
如果用户在输入框输入 john,那么

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