Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does call to jQuery's appendChild fail with undefined error?

Here is my simple HTML:

<body>
    <div id="myParentDivElement">
        Hello World!
    </div>
</body>

Here is the accompanying JavaScript:

$(document).ready(function() {
    var myDOMElement = document.getElementById("myParentDivElement");

    var newDivID = "div_1";
    var newDiv = $('<div id="' + newDivID + '"/>');
    $( newDiv ).css('marginLeft', '50px');

    var newSpanID = "span_1";
    var newSpan = $('<span id="' + newSpanID + '"/>');
    newSpan.text('myLabel');
    newDiv.appendChild(newSpan);   
    $( myDOMElement ).appendChild(newDiv);
});

But when I run this code the line newDiv.appendChild(newSpan); gives the following error:

Uncaught TypeError: undefined is not a function 

Can someone explain why? Here is the JSFiddle showing that it doesn't work: http://jsfiddle.net/TsTMx/2/

like image 651
Saqib Ali Avatar asked May 01 '14 06:05

Saqib Ali


People also ask

How do I fix appendChild is not a function?

To solve the "appendChild is not a function" error, make sure to only call the appendChild method on valid DOM elements and place the JS script tag at the bottom of the body, after the DOM elements have been declared.

What is append and appendChild?

Element.append() allows you to also append string objects, whereas Node.appendChild() only accepts Node objects. Element.append() has no return value, whereas Node.appendChild() returns the appended Node object.

Can you appendChild to a div?

You just need to create another <div> and call appendChild() . The order of event creation doesn't have to be as I have it above. You can alternately append the new innerDiv to the outer div before you add both to the <body> . Save this answer.

What is the opposite of appendChild in Javascript?

The removeChild() method removes an element's child.


2 Answers

Use .append()

newDiv.append(newSpan); 

.appendChild() works with DOM element. newDiv is jQuery Object not a plain JavaScript DOM element.

Working Fiddle

like image 140
Tushar Gupta - curioustushar Avatar answered Oct 06 '22 08:10

Tushar Gupta - curioustushar


.appendChild() is a plain JavaScript method, not jQuery. The jQuery method is .append().

newDiv.append(newSpan);   
$( myDOMElement ).append(newDiv);
like image 18
MrCode Avatar answered Oct 06 '22 09:10

MrCode