What's the difference between:
var div = document.createElement('div');//output -> [object HTMLDivElement]
document.getElementById('container').appendChild(div);
and:
var div = '<div></div>';
document.getElementById('container').appendChild(div);//output -> <div></div>
Shouldn't both be the same? And if not, how do I get the second version to work?
With your JS/DOM engine, calling
Element.appendChild
with astring
as an argument causes a newText
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:
As Sarfraz Ahmed mentioned in his answer, you can make the second example work how you want it to work by writing:
The simplest solution and support all browsers is:
Another solution may be:
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 toinnerHTML
.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:
You can also use these to append/prepend an element to the DOM respectively:
and use the
elem
variable to target the element (e.g):etc.
appendChild
really does expect a HTMLDomNode of some kind, such as aHTMLDivElement
, and not a string. It doesn't know how to deal with a string. You could dobut I really prefer the first version; and I'd rely more on it to behave the same across browsers.