appendChild + createElement

拟墨画扇 提交于 2019-12-28 13:21:31

问题


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?


回答1:


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;



回答2:


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;



回答3:


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.




回答4:


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>');



回答5:


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



回答6:


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.



来源:https://stackoverflow.com/questions/2895318/appendchild-createelement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!