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:
//Appending HTML by replacing the document.body.innerHTML attribute document.body.innerHTML = document.body.innerHTML + "<div>Hello!</div>";
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.
//Create the element using the createElement method. var myDiv = document.createElement("div"); //Set its unique ID. myDiv.id = 'div_id'; //Add your content to the DIV myDiv.innerHTML = "<h1>Hello World!</h1>"; //Finally, append the element to the HTML body document.body.appendChild(myDiv);
- Created a DIV element using the document.createElement() method.
- We modified the element’s ID property and set it to “div_id”.
- Using the innerHTML property, we modified the content of the DIV.
- 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.