An attribute is the initial state when rendered in the DOM. A property is the current state.
In most cases, attributes and properties are kept in-sync automatically. For example, when you use
setAttribute() to update an ID attribute, the
id property is updated as well.
let p = document.querySelector('p'); // Update the ID p.setAttribute('id', 'first-paragraph'); // These both return "first-paragraph" let id1 = p.getAttribute('id'); let id2 = p.id;
However, user-changeable form properties—noteably,
selected—are not automatically synced.
If the user types something into the
#greeting field in this example, using the
Element.setAttribute() method to update the
value will not change what appears in the DOM and will not update the
value property on the element.
<label for="greeting">Greeting</label> <input type="text" id="greeting">
let greeting = document.querySelector('#greeting'); // Update the value greeting.setAttribute('value', 'Hello there!'); // If you haven't made any updates to the field, these both return "Hello there!" // If you HAVE updated the field, val1 returns whatever was typed in the field instead let val1 = greeting.value; let val2 = greeting.getAttribute('value');
If you try to update the
value property directly, that will update the UI.
greeting.value = 'Hello there!';
This often feels like a really silly decision on the part of spec writers. At a minimum, it’s really confusing.
However, it does allow you to choose different approaches depending on whether you want to overwrite user updates or not. If you want to update a field, but only if the user hasn’t made any changes, use
Element.setAttribute(). If you want to overwrite anything they’ve done, use the