Yes, innerHTML
is often misused and a very common source of client-side HTML-injection (DOM-XSS) security holes.
It's usually better to use object-style creation methods, such as createElement
, textContent
and setting direct DOM properties. Similarly in jQuery, prefer to set variable content using .text()
and .prop()
rather than .html()
, or passing HTML markup to the manipulation methods that allow it.
There are some exceptions though:
if you're using a client-side templating language that deals with HTML-escaping for you automatically (eg lodash templates with <%-
), it's safe to write the output to innerHTML
.
if you're appending a lot of siblings to a single element and performance is a priority (the usual example being a <table>
with a large number of rows), HTML markup creation can be worth it and you will just have to be careful to HTML-escape all the text manually
where the content is actually supposed to be HTML, for example you have data that has been processed from Markdown.