What is happening behind .setAttribute vs .attribute=?

input.value is dot notation, it sets the value property of the input object.

It does in no way update any attributes, so trying to get an attribute with the same name will not return the updated value.

If for some reason you have to update the attribute, you would do

input.setAttribute('value', 'new_value');

but you shouldn’t have to use that, as you generally should be working with the properties, not the attributes, and you’d set and get the value property, not the attribute.


An attribute in HTML is a key / value pair inside the opening and closing brackets, as in

<div attribute="attribute_value"></div>

In many cases such attributes will set the initial value of the underlying property, and the property is a named key with a value, that is attached to the internal model of an element, which is what we access with javascript, the object holding the model and data for the element.

Changing any of that objects keys or values does not change the HTML, only the internal representation of the element, the object. However, changing the HTML attributes will in some cases change the object representation of the element.

getAttribute gets the actual attributes from the HTML, not the properties, while element.value clearly accesses a named property in the object representing that element.

Leave a Comment