What\'s the difference between:
var div = document.createElement(\'div\');//output -> [object HTMLDivElement]
document.getElementById(\'container\').appe
With your JS/DOM engine, calling Element.appendChild
with a string
as an argument causes a new Text
node to be created then added.
Your first example creates a <div>
element. Your second example creates a text node with <div></div>
as its contents.
Your second example is equivalent to:
var div = '<div></div>';
document.getElementById('container').appendChild(document.createTextNode(div));//output -> <div></div>
As Sarfraz Ahmed mentioned in his answer, you can make the second example work how you want it to work by writing:
var div = '<div></div>';
document.getElementById('container').innerHTML = div;
appendChild is expecting an element so when you send it text, it doesn't know what to do. You might want to look into using a javascript library to ease some of that work, such as jQuery. Your code would be:
$('#container').append('<div></div>');
The simplest solution and support all browsers is:
var div = '<div></div>';
var parser = new DOMParser();
var myDiv = parser.parseFromString( html, "text/xml" );
Another solution may be:
var div = '<div></div>';
var tmpDiv = document.createElement('div');
tmpDiv.innerHTML = div;
elDiv = tmpDiv.childNodes[0]; //Now it can be used as an element
You can also use these to append/prepend an element to the DOM respectively:
var elem = document.documentElement.appendChild(document.createElement(element));
var elem = document.documentElement.prepend(document.createElement(element));
and use the elem
variable to target the element (e.g):
elem.style.display = "block";
elem.style.remove();
elem.style.id = ...;
etc.
The latter is simply a string containing HTML while the first is an object. For the first, you need appendChild
while for the second, you need to append to innerHTML
.
shouldn't both be the same? and if not, how do i get the 2nd version to work?
var div = '<div></div>';
document.getElementById('container').innerHTML += div;
appendChild
really does expect a HTMLDomNode of some kind, such as a HTMLDivElement
, and not a string. It doesn't know how to deal with a string. You could do
document.getElementById('container').innerHTML += div;
but I really prefer the first version; and I'd rely more on it to behave the same across browsers.