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/
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.
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.
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.
The removeChild() method removes an element's child.
Use .append()
newDiv.append(newSpan);
.appendChild() works with DOM element. newDiv
is jQuery Object not a plain JavaScript DOM element.
Working Fiddle
.appendChild()
is a plain JavaScript method, not jQuery. The jQuery method is .append()
.
newDiv.append(newSpan);
$( myDOMElement ).append(newDiv);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With