Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AppendChild() is not a function javascript

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

like image 333
Neeraj Verma Avatar asked May 15 '14 09:05

Neeraj Verma


People also ask

What is appendChild in Javascript?

appendChild() The appendChild() method of the Node interface adds a node to the end of the list of children of a specified parent node. If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position.

What can I use instead of appendChild?

append() is a convenient alternative to appendChild() . Like appendChild() , append() appends DOM nodes to an element, but unlike appendChild() , append() accepts multiple arguments of any types. The arguments that are not nodes are converted into strings that in turn are converted into text nodes.

What is the opposite of appendChild in Javascript?

removeChild() The removeChild() method of the Node interface removes a child node from the DOM and returns the removed node.

Should I use append or appendChild?

append() can append several nodes and strings, whereas Node. appendChild() can only append one node.


1 Answers

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);
like image 103
MrCode Avatar answered Sep 17 '22 13:09

MrCode