最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - TextNode or innerHTML - Stack Overflow

programmeradmin4浏览0评论

Supposing we have the following element <p id="abc">Hello World</p>. If I want to modify the content in the <p> tag I have two ways in the javascript code:

document.getElementById("abc").innerHTML="good morning";
document.getElementById("abc").firstChild.nodeValue="good morning";

The questions are:

  • Which are the difference between the 2 solutions?
  • Which one should I use? Is there one better than the other?

Supposing we have the following element <p id="abc">Hello World</p>. If I want to modify the content in the <p> tag I have two ways in the javascript code:

document.getElementById("abc").innerHTML="good morning";
document.getElementById("abc").firstChild.nodeValue="good morning";

The questions are:

  • Which are the difference between the 2 solutions?
  • Which one should I use? Is there one better than the other?
Share Improve this question edited Oct 25, 2013 at 10:04 Satpal 133k13 gold badges166 silver badges170 bronze badges asked Oct 25, 2013 at 10:02 zer0unozer0uno 8,03014 gold badges63 silver badges93 bronze badges 1
  • 2 Suggested reading: 1) stackoverflow.com/a/1359822/1273830 2) kellegous.com/j/2013/02/27/innertext-vs-textcontent – Prasanth Commented Oct 25, 2013 at 10:13
Add a comment  | 

1 Answer 1

Reset to default 27

The first one will erase any HTML elements that might be inside your target element. The second will only work if the first child is a text node (a common mistake is to try and use it on an empty element).

The second is "more correct" (innerHTML is really a haxy shortcut) but the first is certainly more reliable. That said, it is vulnerable to XSS injections.

To be completely correct, you would do this:

var abc = document.getElementById('abc');
while(abc.firstChild) abc.removeChild(abc.firstChild);
abc.appendChild(document.createTextNode("good morning"));
发布评论

评论列表(0)

  1. 暂无评论