What's the difference between an "attribute" and a "property" in the DOM?
TL;DR
Attributes are defined in the HTML and provide initial values for properties. Properties are part of the DOM and represent the current state of an element. For example, the value
attribute of an <input>
element sets its initial value, while the value
property reflects the current value as the user interacts with it.
Difference between an "attribute" and a "property" in the DOM
Attributes
Attributes are defined in the HTML markup and provide initial values for elements. They are static and do not change once the page is loaded unless explicitly modified using JavaScript.
Example
In this example, value="initial value"
is an attribute.
Properties
Properties are part of the DOM and represent the current state of an element. They are dynamic and can change as the user interacts with the page or through JavaScript.
Example
In this example, value
is a property of the inputElement
object.
Key differences
- Initialization: Attributes initialize DOM properties.
- State: Attributes are static, while properties are dynamic.
- Access: Attributes can be accessed using
getAttribute
andsetAttribute
methods, while properties can be accessed directly on the DOM object.
Example
In this example, changing the value
property does not affect the value
attribute.