Javascript createElement() is not working in Chrome but it works in IE and Firefox fine. Why?
5 Answers
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.
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); 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>Consult my answer on this question. I had a similar issue. I was creating new input boxes using createElement and had the same issue.
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.