Append HTML to the body using JavaScript.

This is a tutorial on how to append content to the HTML body of a web page using JavaScript. In this guide, I will also tell you why you should avoid using the document.body.innerHTML attribute to accomplish this.

Let’s get started!

Why shouldn’t I use document.body.innerHTML?

On tutorial and help forums such as StackOverflow, you will sometimes come across people recommending the following approach:

In the code above, we appended a DIV to the body tag by replacing the existing HTML with a new string that contains both our old HTML AND the new content that we want to append. However, technically, we are still replacing the content.

As a result, the following issues can occur:

  • The browser will refresh any iframes.
  • Ajax requests that fire once the body has been loaded will be sent again. This is because technically, the body has been loaded again.
  • External widgets, advertisements and analytics code may also be re-loaded again. In certain cases, this can also cause blank advertisements and other display issues.

Basically, it sort of acts like a soft refresh of the page. Except you won’t actually see the refresh happening unless you open up your browser’s developer tools and take a look at the network tab. Consequently, this may cause your page to send a lot of unnecessary HTTP requests to your server. It can also cause a rise in CPU usage as the browser now has to reevaluate the entire DOM again.

To sum it up, it’s not an ideal solution.

The right way to append HTML to the body using JavaScript.

The correct approach is to construct the element using JavaScript’s createElement() method:

In the JavaScript example above, we:

  1. Created a DIV element using the document.createElement() method.
  2. We modified the element’s ID property and set it to “div_id”.
  3. Using the innerHTML property, we modified the content of the DIV.
  4. Finally, we appended the element to our body by using the appendChild() method.

Although this approach is a little more long-winded, it will prevent a situation where Ajax requests are being re-sent. It will also stop your page from unnecessarily reloading iframes or advertisements.

All in all, it is a much better solution than directly editing the document.body.innerHTML property.

Hopefully, this guide saved you from making the same mistake that I did.

Facebook Comments