5

Javascript createElement() is not working in Chrome but it works in IE and Firefox fine. Why?

Alex Shesterov
  • 26,085
  • 12
  • 82
  • 103
Rekha
  • 449
  • 2
  • 15
  • 27

4 Answers4

8

It's working perfectly, use this code:

var catDiv = document.createElement("div");
catDiv.innerHTML = "Test";
document.body.appendChild(catDiv);

Another working example (if you have an element with Id = myTableBody in your HTML)

var appendingTo = document.getElementById("myTableBody");
var tr = document.createElement("tr");
tr.setAttribute("name", "i");
appendingTo.appendChild(tr);
João Louros
  • 2,752
  • 4
  • 23
  • 30
  • I have used like document.createElement(""); I got the error as Uncaught Error: INVALID_CHARACTER_ERR: DOM Exception 5 – Rekha Feb 01 '11 at 12:05
  • @Rekha: Because you have to write `t = document.createElement('tr');` and set the attribute later. Second: table rows have no `name` attribute anyway. You should add your code to your question so that people can *really* help you. – Felix Kling Feb 01 '11 at 12:49
6
var name = document.createElement("Div" ); 

will work. And later you can add the attributes like

name.colSpan="2";
document.body.appendChild(name);

Note: don't try to use angular brackets like createElement("<div />"). It will not work in Chrome.

Edit: syntax issue in above code fixed. there should be a dot instead of comma.

Kurkula
  • 6,386
  • 27
  • 127
  • 202
Krishna K
  • 61
  • 1
  • 3
2

Beacause your code is messed up, there's nothing wrong with "createElement":

<html>
    <head>
        <meta charset = "utf-8">

        <title></title>

        <script>
            window.onload = function () {
                for (var i = 0; i < 100; i ++) {
                    var div = document.createElement ("div");
                        div.style.border = "1px solid black";
                        div.style.margin = "20px";
                        div.style.padding = "10px";

                    document.body.appendChild (div);
                }
            }
        </script>

        <style></style>
    </head>

    <body></body>
</html>

enter image description here

Caio
  • 3,178
  • 6
  • 37
  • 52
1

So I also couldn't get createElement() to work in chrome. After reading Caio's post and testing the code provided I figured out what I was doing wrong.

On w3schools.com the examples they provide always use the tag name in all caps ex. createElement("DIV"), which is the way I was using it and with poor results.

After changing from "DIV" to "div" in my own code it instantly worked.

Thanks Caio.

MikeT
  • 51,415
  • 16
  • 49
  • 68
lonnykight
  • 11
  • 2