JavaScript: Is it better to use innerHTML or (lots of) createElement calls to add a complex div structure? [duplicate]

Depends on what’s “better” for you.

Performance

From a performance point of view, createElement+appendChild wins by a LOT. Take a look at this jsPerf I created when I compare both and the results hit in the face.

innerHTML: ~120 ops/sec
createElement+appendChild: ~145000 ops/sec

(on my Mac with Chrome 21)

Also, innerHTML triggers page reflow.

On Ubuntu with Chrome 39 tests get similar results

innerHTML: 120000 ops/sec
createElement: 124000 ops/sec

probably some optimisation take place.
On Ubuntu with QtWebkit based browser Arora (wkhtml also QtWebkit) results are

innerHTML: 71000 ops/sec
createElement: 282000 ops/sec

it seems createElement faster in average

Mantainability

From a mantainability point of view, I believe string templates help you a lot. I use either Handlebars (which I love) or Tim (for project which need smallest footprints). When you “compile” (prepare) your template and it’s ready for appending it to the DOM, you use innerHTML to append the template string to the DOM. On trick I do to avoid reflow is createElement for a wrapper and in that wrapper element, put the template with innerHTML. I’m still looking for a good way to avoid innerHTML at all.

Compatibility

You don’t have to worry here, both methods are fully supported by a broad range of browsers (unlike altCognito says). You can check compatibility charts for createElement and appendChild.

Leave a Comment