search

Home  >  Q&A  >  body text

javascript - Get attributes in DOM

<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style type="text/css">
        h2 {background:#ccc;}
    </style>
</head>
<body>
    
    <h2 style="font-size:40px; color:red; background-color:black;">js控制行内样式</h2>

    <script type="text/javascript">
        
        var hh2 = document.getElementsByTagName('h2')[0];
    </script>

    <script type="text/javascript">
        
        var h2 = document.getElementsByTagName('h2')[0];

        console.log( h2.style );
        //console.log( h2.style[1] ); //不建议这么用
        console.log( h2.style.color );
    </script>
</body>
</html>
扔个三星炸死你扔个三星炸死你2820 days ago595

reply all(4)I'll reply

  • 欧阳克

    欧阳克2017-06-26 10:59:22

    You can clearly know their relationship by performing an output test on the console:

    h2 is a Dom object,

    style is both an attribute of h2 and h2.style is also an object


    And color is an attribute under style

    So h2.style.color is needed, so h2.style['color'] can also be used


    Supplement: How to output
    Open the browser, press F12, and call the browser debugging tool.

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-06-26 10:59:22

    For example, the nail of your left thumb is represented by the object attribute as you.left.thumb.nail.

    If we just say thumb.nail, who knows which one? Who knows it’s yours...

    So to locate an attribute, we must start from an object (object reference) we know and search downwards.

    By the way, the reference mentioned here is like a pronoun "you", "I", "him", or the name "John", of course, it is generally called a variable in the program.

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-06-26 10:59:22

    What is sub-object?

    There is no conflict between attributes and objects.

    The properties of an object can be of any type. Therefore, the properties of an object can also be an object.

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-06-26 10:59:22

    Style is an attribute of the element, not a global object. You need to obtain the style attribute through the element object first,

    reply
    0
  • Cancelreply