function...">

How to use createElement to create a new table?

Why is the following code not working?

<html>
<head>
    <script type="text/javascript">
    function addTable() {
        var table = document.createElement('table');
        table.innerHTML = "<tr><td>123</td><td>456</td></tr>";
        document.getElementById("addtable").appendChild(table);
    }
    </script>
</head>
<body>
    <input type="submit" value="New Table" onClick="addTable()"/>
    <div id="addtable"></div>
</body>
</html>
+5
source share
1 answer

As far as I know, setting the innerHTML property of an tableelement of a table element or table element (for example, tbodyor thead) does not work in Internet Explorer (EDIT: I just checked - with ietester and simple IE8. The result is an “unknown runtime error” for IE6 and IE8, and this causes IE7 to crash, but it could be an IEtester problem).

DOM insertRow() ( HTMLTableElement HTMLTableSectionElement DOM):

<script type="text/javascript">
function addTable() {
    var c, r, t;
    t = document.createElement('table');
    r = t.insertRow(0); 
    c = r.insertCell(0);
    c.innerHTML = 123;
    c = r.insertCell(1);
    c.innerHTML = 456;
    document.getElementById("addtable").appendChild(t);
}
</script>

script . AFAIK, TBODY, .

EDIT: IE , , innerHTML, html . IE:

<script type="text/javascript">
function addTable() {
    var html = "<table><tr><td>123</td><td>456</td></tr></table>";
    document.getElementById("addtable").innerHTML = html;
}
</script>
+21

All Articles