Home

1 minute read

How to Append HTML to Another Element

Tony Lea

How to Append HTML to Another Element

Appending HTML to the end of another element is very simple. Most people shy away from jQuery nowadays so it's important to know how to append HTML to another element in Vanilla Javascript.

Let's say that you want to append a string of HTML to the end of another element with an id of app, here's how you can accomplish this:

// The HTML string we want to append to our #app element
var htmlString = '<p>Append Me!</p>';

// Get the element we want to append our HTML
var element = document.getElementById('app'); 

// Next, we will create an element that we want append to our #app element
var newElement = document.createElement('div');

// Now, we add our htmlString to our newly created element
newElement.innerHTML = htmlString;

// Finally, we append the new element to our #app element
element.appendChild(newElement);

And that's how simple it is to append an HTML string to another element. We could simplify this even more in a couple lines of code:

var newElement = document.createElement('div');
newElement.innerHTML = '<p>Append Me!</p>';
document.getElementById('app').appendChild( newElement ); 

Finally, there may be a lot of cases where you want to append HTML to the end of the body, and you can do that in a similar way by appending your new element to the document body like so:

// Get the body element
var bodyElement = document.getElementsByTagName("body")[0];

var newElement = document.createElement('div');
newElement.innerHTML = '<p>Append Me!</p>';
bodyElement.appendChild( newElement ); 

Pretty straight forward, right? Happy appending ;)