When to access the attribute (vs the 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

Leave a Comment