Javascript - Append HTML to container element without innerHTML

Bob picture Bob · Jun 10, 2011 · Viewed 356.5k times · Source

I need a way to append HTML to a container element without using innerHTML. The reason why I do not want to use innerHTML is because when it is use like this:

element.innerHTML += htmldata

It works by replacing all of the html first before adding the old html plus the new html. This is not good because it resets dynamic media such as embedded flash videos...

I could do it this way which works:

var e = document.createElement('span');
e.innerHTML = htmldata;
element.appendChild(e);

However the problem with that way is that there is that extra span tag in the document now which I do not want.

How can this be done then? Thanks!

Answer

alnafie picture alnafie · Mar 24, 2012

I am surprised that none of the answers mentioned the insertAdjacentHTML() method. Check it out here. The first parameter is where you want the string appended and takes ("beforebegin", "afterbegin", "beforeend", "afterend"). In the OP's situation you would use "beforeend". The second parameter is just the html string.

Basic usage:

var d1 = document.getElementById('one');
d1.insertAdjacentHTML('beforeend', '<div id="two">two</div>');