Settings

Theme

Why is appending to the innerHTML property bad?

stackoverflow.com

4 points by lucgommans 7 months ago · 2 comments

Reader

lucgommansOP 7 months ago

I knew changing innerHTML had some side effects, but this answer shows just how many corner cases it causes and offers a drop-in replacement at least for appending. Thought other developers on this site would also be interested to learn this

  • baobun 7 months ago

    Deeper than the practical consequences in the answer is the fundamental issue of mixing code with data and operating on the DOM with plaintext HTML like that. It's an antipattern in general. Compare to eval() on JS. Or SQL injection.

    When you're dynamically manipulating a DOM, ideally you want to do so by the more semantic APIs. E.g. https://developer.mozilla.org/en-US/docs/Web/API/Node/append...

    (Not to say that there aren't valid use-cases e.g. when views may be loaded from remotes but if you're constructing the view on the client, best to avoid treating the DOM or its nodes as HTML)

Keyboard Shortcuts

j
Next item
k
Previous item
o / Enter
Open selected item
?
Show this help
Esc
Close modal / clear selection