开发者

Why doesn't Javascript recognize the HTML class attribute?

开发者 https://www.devze.com 2022-12-29 05:06 出处:网络
Can anyone help me with a Javascript question, please? Why does the following code display only message boxes with the word \"null\" in them? And I think there are not enough of them either.

Can anyone help me with a Javascript question, please? Why does the following code display only message boxes with the word "null" in them? And I think there are not enough of them either.

<html>
<head>
    <script type="text/javascript">
        function showElementClasses(node)  {
            var els = node.getElementsByTagName("*");
            for(var i=0,j=els.length; i<j; i++)
                alert(els[i].getAttribute("class"));
                alert("Class: " + els[i].className);
        }

        showElementClasses(document);
    </script>
</head>
<body class="bla">
    <div class="myclass" st开发者_如何转开发yle="width: 500; height: 400" id="map"></div>
</body>
</html>


This works just fine:

<html>
<head>
    <script type="text/javascript">
        function showElementClasses(node)  
        {

            alert("hello, world.");        
            var els = node.getElementsByTagName("*");
            for(var i=0,j=els.length; i<j; i++)
            {
                alert(els[i].getAttribute("class"));
                alert("Class: " + els[i].className);
            }
        }


    </script>
</head>
<body class="bla" onload="showElementClasses(document)">
    <div class="myclass" style="width: 500; height: 400" id="map" ></div>
</body>
</html>


Also you forgot braces after for(var i=0,j=els.length; i<j; i++) and alert("Class: " + els[i].className);.


The only problem is that your alert("Class: " + els[i].className); statement is not being run inside your for loop. You need to correct your braces.

0

精彩评论

暂无评论...
验证码 换一张
取 消