Appending HTML string to the DOM

Šime Vidas picture Šime Vidas · Sep 7, 2011 · Viewed 206.6k times · Source

How to append this HTML string

var str = '<p>Just some <span>text</span> here</p>';

to the DIV with the ID 'test' which is in the DOM?

(Btw div.innerHTML += str; is not acceptable.)

Answer

Neil picture Neil · Sep 7, 2011

Use insertAdjacentHTML if it's available, otherwise use some sort of fallback. insertAdjacentHTML is supported in all current browsers.

div.insertAdjacentHTML( 'beforeend', str );

Live demo: http://jsfiddle.net/euQ5n/