Two words “property” and “attribute” if translated into Vietnamese, we will often translate as the attribute and often we consider them the same. This may be true for other cases, but in case you build web applications with operations related to HTML tags using the DOM (Document Object Model), you should distinguish the differences between them. How different is it in details, we will learn in this tutorial together!
First, I will take an example for you to understand. Assuming I have an HTML page with input as follows :
<input type='text' value='Khanh' />
Let open this page with Chrome, select this input, then right-click and choose Inspect input and then select Console, you will see the following result:
We will use the “$0” character to get the information about the current HTML tag that we are manipulating. In my example will be the input tag, as follows:
If you now get information about the input tag’s “value” attribute with getAttribute() method, you will see the following result:
This is the value of the “value” attribute in that input tag. One thing to keep in mind: once initialized, the value of any HTML attribute will not change.
The DOM object for this input tag is also initialized with property (value, type) corresponding to the attributes are as follows:
We can change the value of properties in the DOM object, but this change, as I said above, will not change the value of the attributes.
If now, I change the value of the input tag to “Huong Dan Java”, you will see the input tag’s “value” attribute remains unchanged, but the “value” property value of the DOM object changes to the following “Huong Dan Java”:
In short, attribute and property are two completely different concepts in web programming!