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 in 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 search for 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"
Namely the .getAttribute
retrieves information from HTML that is static, not the DOM object that has already changed value.
Using setAttribute will change the HTML attribute and has some different effects. For example input.setAttribute("disabled", false);
will do the opposite of expected, will block the element whereas input.disabled = false;
will do what is expected.. This is because the browser detects the presence of the attribute disabled
and does not read the value of this attribute (only its presence). Changing the property .disabled
directly changes the behavior in the element.
A another example clarifies the difference between HTML and the Javascript representation of what goes on in 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
for the 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 a 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 the two in the code because it can generate very difficult bugs to detect.
Apart from the errors that can be generated by setAttribute
access the property of the object representing the DOM element is also faster.
has a comparative in jsperf: http://jsperf.com/setattribute-vs-property-assignment/7. In terms of performance, direct access is faster.
– Tobias Mesquita