I gather from this post that almost always one wants to be accessing the DOM property, not the HTML attribute.
So what are the rare useful exceptions? In what situation is accessing the HTML attribute better than accessing the DOM property?
Sometimes the attribute doesn't map to changes in the property.
One example is the checked
attribute/property of a checkbox.
DEMO: http://jsfiddle.net/mxzL2/
<input type="checkbox" checked="checked"> change me
document.getElementsByTagName('input')[0].onchange = function() {
alert('attribute: ' + this.getAttribute('checked') + '\n' +
'property: ' + this.checked);
};
...whereas an ID attribute/property will stay in sync:
DEMO: http://jsfiddle.net/mxzL2/1/
<input type="checkbox" checked="checked" id="the_checkbox"> change me
var i = 0;
document.getElementsByTagName('input')[0].onchange = function() {
this.id += ++i;
alert('attribute: ' + this.getAttribute('id') + '\n' +
'property: ' + this.id);
};
And custom properties generally don't map at all. In those cases, you'll need to get the attribute.
Perhaps a potentially more useful case would be a text input.
<input type="text" value="original">
...where the attribute doesn't change with changes from the DOM or the user.
As noted by @Matt McDonald, there are DOM properties that will give you the initial value that would reflect the original attribute value.
HTMLInputElement.defaultChecked
HTMLInputElement.defaultValue
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With