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?
In the first example you’re not accessing to the
styleattribute, but to thestyleproperty. The property’s value can be anything, in case of thestyleproperty 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
styleon a HTML node, yourstyleproperty 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):