简体   繁体   中英

Javascript createElement() not working in Chrome

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

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);

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>

在此输入图像描述

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.

Consult my answer on this question. I had a similar issue. I was creating new input boxes using createElement and had the same issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM