appendChild + createElement

2020-02-04 07:16发布

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?

6条回答
Bombasti
2楼-- · 2020-02-04 07:54

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;
查看更多
Evening l夕情丶
3楼-- · 2020-02-04 08:09

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
查看更多
SAY GOODBYE
4楼-- · 2020-02-04 08:14

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;
查看更多
一纸荒年 Trace。
5楼-- · 2020-02-04 08:14

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>');
查看更多
迷人小祖宗
6楼-- · 2020-02-04 08:15

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.

查看更多
等我变得足够好
7楼-- · 2020-02-04 08:16

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.

查看更多
登录 后发表回答