使用JavaScript向DOM添加元素



我已经尝试过了:

let x = document.createElement('p');
let y = document.createTextNode('Hello world');
x.appendChild(y);
document.body.appendChild(x);

为什么不起作用?

您不应该使用createTextNote,而应该使用:

let x = document.createElement('p');
x.innerHtml = /* your text */;
document.body.appendChild(x);

x.innerHtml设置p元素的内部内容,在本例中它是一些文本。

最新更新