All Articles

DOM insert HTML method you might not know

Everybody knows/use “innerHTML” to insert HTML but I was looking at the MDN website jumping between Web API’s when I saw this DOM method called’s “innerHTML” brothers but cooler and faster.
Besides the performance another difference is that “innerHTML” will overwrite the content inside the element when “insertAdjacentHTML” will add to the specified position.

Here you can compare the performance between “innerHTML” and “insertAdjacentHTML” here and gets better its supported in all browsers.

It’s been out there for a while now even John Resig has an post about it back in 2008.

It’s very simple to use you are going to need to pass one of the positions (below) and then pass the content.


  • “beforebegin” (insert before the element)
  • “afterend” (insert after the element)
  • “afterbegin” (insert inside element after begin)
  • “beforeend” (insert inside element before end)
element.insertAdjacentHTML("position", "content");

Let’s say we have a method that do the job for us when we pass the “position” and “content”.

(function(window) {
	window.App = window.App || {};

	window.App = {
		insertElement: function(position, content) {
			var elDiv = document.getElementById('wrapper');
				elDiv.insertAdjacentHTML(position, content)

var content1 = '<p id="ct1">this is a paragrag a "beforebegin" element</p>';
var content2 = '<p id="ct2">this is a paragrag a "afterbegin" element</p>';
var content3 = '<p id="ct3">this is a paragrag a "beforeend" element</p>';
var content4 = '<p id="ct4">this is a paragrag a "afterend" element</p>';

App.insertElement('beforebegin', content1);
App.insertElement('afterbegin', content2);
App.insertElement('beforeend', content3);
App.insertElement('afterend', content4);

Here’s a example how it works link.

Enjoy the tip.

Published 8 Jan 2014

Software Engineer focused in Javascript applications
Michael Lancaster on Twitter