Difference between Attribute and Property in HTML world
Attributes are defined by HTML. Properties are accessed from DOM (Document Object Model) nodes.
While writing HTML code, you can define attributes on your HTML elements. Then, once the browser parses your code, a corresponding DOM node will be created. This node is an object, and therefore it has properties.
- A few HTML attributes have 1:1 mapping to properties; for example,
id
. - Some HTML attributes don’t have corresponding properties; for example,
aria-*
. - Some DOM properties don’t have corresponding attributes; for example,
textContent
.
Let’s discuss further:
<input type="text" value="Name:">
There are 2 attributes, type and value.Also it has 2 properties,type and value.
Let’s take another example:
<input id="inputId" type="text" value="Name:">
The id
property is a reflected property for the id
attribute.Getting the property reads the attribute value, and setting the property writes the attribute value.
Let’s talk about the type property.
The type
property is a reflected property for the type
attribute.
Let’s take about how to get values of an attribute and a property:<input id="inputId" type="number" value="Name:">
var element = document.getElementById(“inputId”);
element.getAttribute(“type”) will give “number” and element.type will give “text” because the initial value we have provided is a text.
Same is the case with value property. Imagine that an user has given input text as “hello”, then,
element.getAttribute(“value”) will give “Name:
”,since we have provided “Name:
” as initial attribute value and element.value will give “hello”.
So, the value
property reflects the current text-content inside the input box, whereas the value
attribute contains the initial text-content of the value
attribute from the HTML source code