Can createElement method be applied on any node other than document?

时间:2018-02-03 09:24:40

标签: javascript html createelement

 <html>
    <body>
        <style>
        .dot{
        width: 8px;
        height: 8px;
        border-radius: 4px;
        background-color: red;
        display: inline-block;
        }
        </style>

        <script>
        var dots = document.createElement("div");
        dots.className = "dots";
        document.body.appendChild(dots);

        var dot = document.body.createElement("div");
        </script>
    </body>
</html>

In the above segment,I tried creating a div node with variable name "dots" which was successful.But when I tried to create a div node with variable name "dot" using document.body.createElement,my attempt failed.Is it because that createElement method is supported only for document object and from there other nodes should be appended?

1 个答案:

答案 0 :(得分:2)

As Barmer already commented, createElement only exists on Document: https://wiki.selfhtml.org/wiki/JavaScript/DOM/Document

To append it to the body tag of your DOM, you use appendChildof Node: https://wiki.selfhtml.org/wiki/JavaScript/DOM/Node/appendChild

So your own answer is correct