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
296 views
in Technique[技术] by (71.8m points)

html - Different ways of accessing attribute values using javascript

document.getElementById('myId').style;

is one way of accessing the style attribute.. Also we can do the same using document.getElementById('myId').getAttribute('style');

What is the difference between these two ways of getting attribute values..And which one is preferable?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

In the first example you're not accessing to the style attribute, but to the style property. The property's value can be anything, in case of the style property is an object. In the second example you're accessing to the style attribute of the tag. The attribute's value can be only string.

In case of some attributes there is a mapping between them. So if you set an attribute style on a HTML node, your style property is updated and your style is applied. However, this is not always true: a well known bug in some versions of IE (at least till IE7) is that sort of mapping is broken, so set an attribute is not reflected to the property.

So, if you want set an attribute on a HTML node, you have to use the second one. But if you want to access to the property of your object that represent a HTML node, you have to use the first one.

In case of the style, the first one is strongly recommended.

To make it clear with an example (in modern browsers):

document.body.style.border = "1px solid red";
console.log(document.body.style); // [object CSSStyleDeclaration]
console.log(document.body.getAttribute("style")); // "border: 1px solid red;"

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

...