DOM insert HTML method you might not know

Cover Image for 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 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 = '<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.

More Stories

Cover Image for Using ChatGPT as your nutritionist

Using ChatGPT as your nutritionist

While ChatGPT is primarily known for its conversational abilities, it can also serve as a virtual trainer and nutritionist, providing personalized guidance to help you achieve your health and wellness goals.

Cover Image for How to invest in the stock market - a beginners guide

How to invest in the stock market - a beginners guide

There is so much bad information on how to invest in stock market causing a lot of confusion for people that want to get started in investing that I decided to create a guideline for beginners based on Peter Lynch work