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.
Now, let us consider that the user inputs “1234”, then the element.getAttribute(“value”) will return “Phone Number:” because we have provided this as the initial value of this attribute. But element.value will return “1234”.
Thus, the value attribute has the initial text-content that was provided by the developer in the HTML source code because the value property reflects the current text-content inside the input box (provided by the user in this case).
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:
Attribute Property 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.