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

前端 未结 3 1649
攒了一身酷
攒了一身酷 2020-12-05 10:11

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

相关标签:
3条回答
  • 2020-12-05 10:42

    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.

    0 讨论(0)
  • 2020-12-05 10:43

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

    0 讨论(0)
  • 2020-12-05 10:49

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

    • elem.createTextNode(text) and elem.textContent = text do the exact same thing (src: https://javascript.info/task/createtextnode-vs-innerhtml)

    • While textContent returns the full text contained in a node, innerText returns only the visible text contained in the node. (src: Difference between textContent vs innerText)

    0 讨论(0)
提交回复
热议问题