Search code examples
javascripthtml-tablegetelementsbytagname

Why doesn't getElementsByTagName work in this logic?


Just testing this out, trying to insert a table into the body tag but I can only do it with getElementById. I also tried inserting the script code at the bottom, but that doesn't work either.

<html>

<head>
        <title>Exam Test Trial</title>
        <script>
        var table;
            var books = {1234: "Programming for Dummies", 5667: "Ethical Hacking", 88889: "Networks", 10000: "Firmware Code"};

                function createTable(){
                table = "<table border= '1'>";

                table += "<tr>";

                for(var isbn in books){
                    table += "<th>";
                    table += isbn;
                    table += "</th>";
                }

                table += "</tr>";
                table += "</table>";


                //var x = document.getElementById("exam").innerHTML = table;

                var y;
            }


        </script>
</head>

<body id="exam">
    <script>
        createTable();
        var x = document.getElementsByTagName("body").innerHTML = table;
    </script>
</body>


Solution

  • getElementsByTagName("body") returns an array-like structure. Did you mean getElementsByTagName("body")[0], perhaps?