Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to access the attribute (vs the property)?

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?

like image 684
Randomblue Avatar asked Sep 28 '11 19:09

Randomblue


1 Answers

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
like image 63
user113716 Avatar answered Oct 15 '22 16:10

user113716