37

The title is pretty clear: Is there any major difference between innerHTML and createTextNode (used with Append) to fill a span with text?

Jeff Noel
  • 7,500
  • 4
  • 40
  • 66
  • 3
    What? createTextNode() is several magnitudes faster than innerHTML when appending text to a node. See http://jsperf.com/innerhtml-and-createtextnode – devnull69 Oct 29 '12 at 13:55
  • @devnull69 That test is specifically for appending new content multiple times (and computing HTML additions will naturally be slower). But simply adding text is very equal (innerHTML is actually a tiny bit faster): http://jsperf.com/innerhtml-and-createtextnode/2 – David Hellsing Oct 29 '12 at 14:28
  • on my machine, createTextNode in your example is still twice as fast as innerHTML (Win7 32 Enterprise, Firefox) – devnull69 Oct 29 '12 at 14:31
  • @devnull69 yea, actually the results fluctuate a lot, I sometimes get innerHTML slightly faster, but sometimes the other way around. Anyway, my point is that the there is likely no "major difference" as the OP asked for. – David Hellsing Oct 29 '12 at 14:34

3 Answers3

44

Of course. createTextNode will escape any strings and show them as they are, while innerHTML could render html-like strings into a DOM. If you don't want that (unless you are sure the text contains no unescaped tags, e.g. when assigning a literal directly), you can use textContent (or innerText for IE).

Yet I'd recommend createTextNode, because all browsers support it equally without any quirks.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • "*...to fill a span with text*" – Šime Vidas Oct 29 '12 at 13:51
  • 4
    Yes. But *text* could contain tags etc (you never know), so I'd expect the OP to use `innerText`/`textContent` at least – Bergi Oct 29 '12 at 13:54
  • 1
    @Bergi—you should update your answer to include textContent/innerText as an alternative (perhaps even preferred). – RobG Oct 29 '12 at 13:58
  • @Bergi `textContent`, and `innerText` are not cross-browser, so one would have to resort to a shim. I'd just use `innerHTML` instead. – Šime Vidas Oct 29 '12 at 14:17
  • Beware that contrary to `innerContext`, `innerText` is aware of CSS styling and will trigger a reflow. https://developer.mozilla.org/en-US/docs/Web/API/Node.textContent Do not recommend them as interchangeable. – Gajus Oct 19 '14 at 19:04
  • @GajusKuizinas: Thanks for being alert, but we're talking about *setting* it – Bergi Oct 19 '14 at 21:04
  • @Bergi which setting it would trigger a reflow, correct? – adam-beck May 25 '16 at 12:45
  • @adam-beck: Not immediately, no. It'll happen only when JS has stopped execution and does no more change the DOM. – Bergi May 25 '16 at 12:47
3

Doing some research online, here's what I've found. This should cover it at a high level:

venkat0591
  • 31
  • 1
0

My understanding is that certain manipulations of innerHTML remove all bound events, so using createTextNode is preferable.

jeesty
  • 1,124
  • 1
  • 10
  • 13