AppendChild() is not a function javascript

2020-02-09 07:53发布

this is my javascript

<head runat="server">
    <script type="text/javascript" language="javascript">

        function createQuestionPanel() {

            var element = document.createElement("Input");
            element.setAttribute("type", "button");
            element.setAttribute("value", "button");
            element.setAttribute("name", "button");


            var div = '<div>top div</div>';
            div[0].appendChild(element);

        }

        function formvalidate() {

        }

    </script>
</head>
<body onload="createQuestionPanel()">
</body>
</html>

it is throwing error "AppendChild is not a function" . I tried to search for solution .. it was suggested that on the place of

div.appendChild(element);

this should be posted

div[0].appendChild(element);

it didnt change the error . Please suggest

5条回答
欢心
2楼-- · 2020-02-09 08:17

Your div variable is a string, not a DOM element object:

var div = '<div>top div</div>';

Strings don't have an appendChild method. Instead of creating a raw HTML string, create the div as a DOM element and append a text node, then append the input element:

var div = document.createElement('div');
div.appendChild(document.createTextNode('top div'));

div.appendChild(element);
查看更多
成全新的幸福
3楼-- · 2020-02-09 08:18

Try the following:

var div = document.createElement("div");
div.innerHTML = "topdiv";
div.appendChild(element);
document.body.appendChild(div);
查看更多
够拽才男人
4楼-- · 2020-02-09 08:24

In this

var div = '<div>top div</div>';

"div" is not a DOM object,is just a string,and string has no string.appendChild.

Here are some references that may help you on appendChild method:

<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);

var element = document.getElementById("div1");
element.appendChild(para);
</script>
查看更多
Bombasti
5楼-- · 2020-02-09 08:38

Just change

var div = '<div>top div</div>'; // you just created a text string

to

var div = document.createElement("div"); // we want a DIV element instead
div.innerHTML = "top div";
查看更多
看我几分像从前
6楼-- · 2020-02-09 08:41
 function createQuestionPanel() {

        var element = document.createElement("Input");
        element.setAttribute("type", "button");
        element.setAttribute("value", "button");
        element.setAttribute("name", "button");


        var div = document.createElement("div"); <------- Create DIv Node
        div.appendChild(element);<--------------------
        document.body.appendChild(div) <------------- Then append it to body

    }

    function formvalidate() {

    }
查看更多
登录 后发表回答