What is the difference between properties and attributes in HTML?
DOM: It is the acronym for the Document Object Model. When the browser parses your HTML code, it creates a corresponding DOM node. The HTML properties are accessed from this node object.
- Some DOM properties don’t possess corresponding attributes.
- Some HTML attributes don’t possess corresponding properties.
- Some HTML attributes, like ‘class’, possess 1:1 mapping to properties.
Let us take a look at some quick examples to demonstrate the differences between attributes and properties.
Example: Consider the following HTML code snippet.
In the webpage above, let us consider that the user inputs “1234” into the input field. Getting the value of the “value” attribute via element.getAttribute(“value”) would return “Phone Number:” because we have provided this as the initial value of this attribute in the source code. But getting the value of the “value” property via element.value will return “1234” because the “value” property gets updated with the new value, but not the “value” attribute.
Now we have a basic idea about the difference, let us dive deep and learn about more differences.
Attribute: Attributes are defined by HTML and are used to customize a tag.
The output is 2 because the two attributes are: id=”AttributeDemo” and onclick=”myFunction()”.
Note: The document.getElementsById(‘AttributeDemo’).attributes code snippet returns a collection of the specified node’s attributes, as a NamedNodeMap object. To access the nodes, we can use the generic indexing method. Replace the following line in the above code snippet.
The attributes have a data type of string. So no matter the value of the attribute, it will always return a string.
Default attributes (non-user-defined) change when corresponding property changes and vice-versa.
- Non-custom attributes (like id, class, etc.) have 1:1 mapping to the properties.
- Attributes that have a defined default value remain constant when the corresponding property changes.
Difference between HTML attributes and DOM properties:
|Attributes are defined by HTML.||Properties are defined by the DOM.|
|The value of an attribute is constant.||The value of a property is variable.|
|These are used to initialize the DOM properties. After initialization, the job is finish. ||No such job defined.|