TL; DR
HTML elements have attributes. When we represent these in JavaScript we get objects with properties.
-
.setAttribute
changes in HTML, is slower and blind
-
.prop
changes directly on the DOM object, faster
Starting from this HTML:
<input type="text" value="Escreve o teu nome" />
If I write my name in this input, and fetch its current value via JavaScript, notice what I get:
input.value = 'Sérgio';
input.value; // dá "Sérgio"
input.getAttribute('value'); // dá "Escreve o teu nome"
In other words, .getAttribute
will fetch the information from the HTML that is static, not the DOM object that has already changed its value.
Using setAttribute will change the HTML attribute and in some cases have different effects. For example input.setAttribute("disabled", false);
will do the opposite of expected, will block the element while input.disabled = false;
will do what is expected. . This is because the browser detects the presence of the disabled
attribute and does not read the value of that attribute (only its presence). Changing the .disabled
property directly changes the behavior in the element.
A other example clarifies the difference between HTML and JavaScript representation of what goes on in the DOM:
var input = document.querySelector('input');
input.setAttribute('dataA', 'foo');
console.log(1, input.dataA, input.parentNode.innerHTML);
// dá: 1 undefined "<input type="text" value="Escreve o teu nome" dataa="foo">"
input.dataB = 'foo';
console.log(2, input.dataB, input.parentNode.innerHTML);
// dá 2 "foo" "<input type="text" value="Escreve o teu nome" dataa="foo">
In the first case the HTML element receives a new attribute dataa
and not dataA
because setAttribute
is case-insensitive and the value "set" is not returned by input.dataA
, nor input.dataa
.
In the second case, the .dataB
is added as the new object property in JavaScript but is not reproduced in HTML. It is only on the JavaScript side and is not written in HTML.
It is good practice to change the property directly and not mix both in the code as it can generate very difficult bugs to detect.
Apart from the errors that can be generated by setAttribute
accessing the property of the object representing the DOM element is also faster .