HTML DOM innerHTML属性

时间:2016-09-07 12:52:29

标签: javascript html dom

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

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

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

3 个答案:

答案 0 :(得分:2)

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

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

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

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

另一种方法

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

答案 1 :(得分:0)

作为MDN says:

  

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

答案 2 :(得分:0)

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