DOM insert HTML method you might not know

08 Jan 14

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 insertAdjacentHTML..it'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.

Position

  • "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)
        }
    }
})(window);

var content1 = '

this is a paragrag a "beforebegin" element

'; var content2 = '

this is a paragrag a "afterbegin" element

'; var content3 = '

this is a paragrag a "beforeend" element

'; var content4 = '

this is a paragrag a "afterend" element

'; 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.

comments powered by Disqus