Is there any major difference between innerHTML and using createTextNode to fill a span?
Asked Answered
C

3

38

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

Cannabis answered 29/10, 2012 at 13:39 Comment(4)
What? createTextNode() is several magnitudes faster than innerHTML when appending text to a node. See jsperf.com/innerhtml-and-createtextnodeOpportina
@Opportina 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): jsperf.com/innerhtml-and-createtextnode/2Foreshadow
on my machine, createTextNode in your example is still twice as fast as innerHTML (Win7 32 Enterprise, Firefox)Opportina
@Opportina 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.Foreshadow
M
46

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.

Merlinmerlina answered 29/10, 2012 at 13:50 Comment(8)
"...to fill a span with text"Kettie
Yes. But text could contain tags etc (you never know), so I'd expect the OP to use innerText/textContent at leastMerlinmerlina
@Bergi—you should update your answer to include textContent/innerText as an alternative (perhaps even preferred).Lessen
@Merlinmerlina textContent, and innerText are not cross-browser, so one would have to resort to a shim. I'd just use innerHTML instead.Kettie
Beware that contrary to innerContext, innerText is aware of CSS styling and will trigger a reflow. developer.mozilla.org/en-US/docs/Web/API/Node.textContent Do not recommend them as interchangeable.Filterable
@GajusKuizinas: Thanks for being alert, but we're talking about setting itMerlinmerlina
@Merlinmerlina which setting it would trigger a reflow, correct?Stanger
@adam-beck: Not immediately, no. It'll happen only when JS has stopped execution and does no more change the DOM.Merlinmerlina
R
3

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

Roofdeck answered 24/5, 2019 at 2:32 Comment(0)
A
0

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

Attend answered 9/5, 2015 at 18:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.