Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextNode or innerHTML

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?
like image 222
zer0uno Avatar asked Oct 25 '13 10:10

zer0uno


1 Answers

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"));
like image 69
Niet the Dark Absol Avatar answered Sep 28 '22 11:09

Niet the Dark Absol