Search code examples
javascripthtmldombrowser

Appending HTML string to the DOM


How to append a HTML string such as

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

to the <div> with the id test?

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


Solution

  • Use insertAdjacentHTML which is supported in all current browsers:

    div.insertAdjacentHTML( 'beforeend', str );
    

    The position parameter beforeend will add inside the element, after its last child.

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