Different ways of accessing attribute values using javascript

前端 未结 4 878
生来不讨喜
生来不讨喜 2020-12-14 18:02
document.getElementById(\'myId\').style;

is one way of accessing the style attribute.. Also we can do the same using document.getElementById

相关标签:
4条回答
  • 2020-12-14 18:17

    Yes there is no difference and detailed example can be found on the following link: https://developer.mozilla.org/en/DOM/element.style#Example

    0 讨论(0)
  • 2020-12-14 18:30

    there is no difference.

    document.getElementById('myId').style;
    

    is a shorthand for

    document.getElementById('myId').getAttribute('style');
    

    the only use for getAttribute('attributeName') would be if attributeName is not a valid javascript variable name, so encapsulating it in quotes would be the only way to access it.

    0 讨论(0)
  • 2020-12-14 18:33

    getAttribute will return the value of non-standard attributes as well as standard ones.

    Object property notation will not, since non-standard attributes aren't converted to properties.

    <a id="test" foo="bar"> ... </a>​
    
    <script>
    
        console.log(document.getElementById('test').foo); // undefined
    
        console.log(document.getElementById('test').getAttribute('foo')); // "bar"
    
    </script>
    
    0 讨论(0)
  • 2020-12-14 18:38

    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;"
    
    0 讨论(0)
提交回复
热议问题