Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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') + '
' +
          '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') + '
' +
          '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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...