preface
An attribute is a feature on an HTML tag, which is a key-value pair commonly seen in HTML code
Property is a property in the DOM, an object in JavaScript
The sample
Attributes always hold their original values in the HTML code, and properties can change.
<input id="the-input" type="typo" value="Name:" customAttr="customAttr" />
// After the page loads, type "Jack" in the input.
// The type attribute gives the value typo, which is not the type supported by input
input.getAttribute('id') // the-input
input.getAttribute('type') // typo
input.getAttribute('value') // Name:
input.getAttribute("customAttr") // customAttr
input.id // the-input
input.type // text
input.value // Jack
inout.customAttr // undefined
Copy the code
In attribute, the value is still the value in the HTML code, while in property, type is modified to text, and the value of the value changes accordingly to user input.
A custom attribute can be successfully obtained, but a property cannot be obtained.
When a DOM node is initialized, attributes defined in the HTML specification are assigned to the property. Custom attributes do not fall within this range, and naturally generated DOM nodes do not have this property.
The difference between
Attribute
-
The value can only be string
-
If you set an attribute value for an element when editing HTML, the attribute value remains the default value even if the value is later changed.
-
Allows the creation of custom values
property
-
Values can be of any type: Boolean, string, number, etc
-
It can be accessed through DOM objects
-
There may be no custom attributes other than those specified
reference
Attribute VS Property
Attribute and Property