0

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" style="width: 500; height: 400" id="map"></div>
</body>
</html>
2
  • 1
    Is * a valid wildcard character? Also, your for loop needs more braces. Commented May 3, 2010 at 22:45
  • 1
    The * is correct (w3.org/TR/REC-DOM-Level-1/…), the braces aren't. Commented May 3, 2010 at 22:46

3 Answers 3

2

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much! Why does it only work if the call is put into the onload attribute? Is the <script> executed before the <body> is even created?
Putting the call in the onload for the body tag insures that all of the tags in the entire document are loaded before you try to 'getElementsByTagName' for that document (unless you have elements AFTER the body tag ends, which isn't likely) since the body tag is the last tag in the document. Yes, you're correct, the script call is executed as soon as the line is parsed inside the script call so it's going to cause some problems for that method.
2

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

1 Comment

Seems like I've been working with Python too much lately :) Thank you!
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.