To understand the difference it is necessary to take into account that HTML and Javascript are different languages.
Thus:
- HTML has elements with attributes
- Javascript has objects with properties
The DOM is the interception between Javascript and HTML, something that there is for example in Node.js. So the DOM objects that Javascript has access to have properties that are the representation of HTML attributes.
Objects that do not have the property of a given attribute defined Javascript uses the attribute value.
Examples:
var a = document.getElementById('a');
var b = document.getElementById('b');
var c = document.getElementById('c');
console.log(a.checked, a.disabled); // true false
console.log(b.checked, b.disabled); // false true
c.setAttribute('disabled', true);
c.checked = true;
console.log(c.checked, c.disabled); // true true
<input checked="checked" type="checkbox" id="a"/>
<input disabled type="checkbox" id="b"/>
<input type="checkbox" id="c"/>
The example a
and b
behave as expected, Javascript reads the properties importing the value of the attributes of the HTML element.
The example c
has nothing defined in HTML but we assign value to checked
and disabled
changing object property, Resp. html attribute.
Another example:
var c = document.getElementById('c');
c.checked = false;
console.log(c.checked, c.getAttribute('checked')); // false true
<input checked="true" type="checkbox" id="c" />
In this example above the difference becomes even clearer, the .checked
(object property) changes the value only in Javascript and not in HTML where the attribute remains with the initial value.
Excellent explanation, thank you very much.
– Velasco
@Velasco of nothing, good question!
– Sergio