appendChild + createElement

后端 未结 6 790
轻奢々
轻奢々 2020-12-09 09:54

What\'s the difference between:

var div = document.createElement(\'div\');//output -> [object HTMLDivElement]

document.getElementById(\'container\').appe         


        
6条回答
  •  被撕碎了的回忆
    2020-12-09 10:07

    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

    element. Your second example creates a text node with
    as its contents.

    Your second example is equivalent to:

    var div = '
    '; document.getElementById('container').appendChild(document.createTextNode(div));//output ->

    As Sarfraz Ahmed mentioned in his answer, you can make the second example work how you want it to work by writing:

    var div = '
    '; document.getElementById('container').innerHTML = div;

提交回复
热议问题