HTML DOM innerHTML Property

HTML DOM innerHTML Property

本文关键字:Property innerHTML DOM HTML      更新时间:2023-09-26

使用id="demo":更改<p>元素的HTML内容

document.getElementById("demo").innerHTML = "Paragraph changed!";

这是更改html内容的正确方法吗

如果只想更改内容,请使用

document.getElementById("demo").innerText = "Paragraph changed!";

或者你想改变html标签也使用,

document.getElementById("demo").innerHTML  = "<h2>Heading changed!</h2>";

另一种方法

document.getElementById("demo").firstChild.nodeValue = "Paragraph changed!";

正如MDN所说:

此属性提供了一种简单的方法来完全替换元素的内容。

In this syntax example, {ID of element} is the ID of an HTML element and {content} is the new content to go into the element.
document.getElementById('{ID of element}').innerHTML = '{content}';
Now for your Issue,just do this
document.getElementsByTagName("P")[0].innerHTML = "Paragraph changed!"; [OR] document.getElementById("demo").innerHTML = "Paragraph changed!";

FiddleLink