Description:
I am using simple javascript to set a the value of an input. I am using multiple methods that appear to be th
It's important to take note of the differences between attributes and properties.
value attributeThe value attribute of an , visible in the HTML representation of the element, is mapped to the defaultValue property. For example:
var i = document.createElement('input');
i.setAttribute('value', 'foo');
console.log(i.defaultValue, i.getAttribute('value')); // "foo foo"
i.defaultValue = 'bar';
console.log(i.defaultValue, i.getAttribute('value')); // "bar bar"
value propertyThe value property mirrors the defaultValue property (and value attribute) until it's explicitly been given a value, so:
var i = document.createElement('input');
i.defaultValue = 'foo';
console.log(i.value); // "foo"
i.value = 'bar';
i.defaultValue = 'foo';
console.log(i.value); // "bar"
This is another way of looking at it:
↑↓
input.defaultValue = "foo";
↓
input.value
get(): value === undefined ? input.defaultValue : value
set(newValue): value := newValue
When using anchors, the href attribute and href property update each other, but in a different way, e.g.:
var a = document.createElement('a');
a.setAttribute('href', '/test');
console.log(a.href); // "http://stackoverflow.com/test"
a.href = '/test';
console.log(a.getAttribute('href')); // "/test"
Here's a (partial) list of attributes and their corresponding properties:
element | attribute | property
---------+-----------+----------------
option | selected | defaultSelected (bool)
label | for | htmlFor
input | checked | defaultChecked (bool)
select | multiple | multiple (bool)
li | value | value (int)
As you can see, whereas the attributes are always strings, the corresponding properties may be of other types.