Here's some sample code:
function addTextNode(){
var newtext = document.createTextNode(" Some text added dynamically. ");
var para = document.getElementById("p1");
para.appendChild(newtext);
$("#p1").append("HI");
}
<div style="border: 1px solid red">
<p id="p1">First line of paragraph.<br /></p>
</div>
What is the difference between append()
and appendChild()
?
Any real time scenarios?
This question is related to
javascript
jquery
append
appendchild
now append is a method in JavaScript
MDN documentation on append method
Quoting MDN
The
ParentNode.append
method inserts a set of Node objects orDOMString
objects after the last child of theParentNode
.DOMString
objects are inserted as equivalent Text nodes.
This is not supported by IE and Edge but supported by Chrome(54+), Firefox(49+) and Opera(39+).
The JavaScript's append is similar to jQuery's append.
You can pass multiple arguments.
var elm = document.getElementById('div1');
elm.append(document.createElement('p'),document.createElement('span'),document.createElement('div'));
console.log(elm.innerHTML);
_x000D_
<div id="div1"></div>
_x000D_
appendChild
is a DOM vanilla-js function.
append
is a jQuery function.
They each have their own quirks.
appendChild
is a pure javascript method where as append
is a jQuery method.
The JavaScript appendchild method can be use to append an item to another element. The jQuery Append element does the same work but certainly in less number of lines:
Let us take an example to Append an item in a list:
a) With JavaScript
var n= document.createElement("LI"); // Create a <li> node
var tn = document.createTextNode("JavaScript"); // Create a text node
n.appendChild(tn); // Append the text to <li>
document.getElementById("myList").appendChild(n);
b) With jQuery
$("#myList").append("<li>jQuery</li>")
append
is a jQuery method to append some content or HTML to an element.
$('#example').append('Some text or HTML');
appendChild
is a pure DOM method for adding a child element.
document.getElementById('example').appendChild(newElement);
I know this is an old and answered question and I'm not looking for votes I just want to add an extra little thing that I think might help newcomers.
yes appendChild
is a DOM
method and append
is JQuery method but practically the key difference is that appendChild
takes a node as a parameter by that I mean if you want to add an empty paragraph to the DOM you need to create that p
element first
var p = document.createElement('p')
then you can add it to the DOM whereas JQuery append
creates that node for you and adds it to the DOM right away whether it's a text element or an html element
or a combination!
$('p').append('<span> I have been appended </span>');
Source: Stackoverflow.com