Append or prepend to an element

Insert a new element or an HTML structure to the end or the beginning of another element's content.


Using the property innerHTML of an element to get or modify its content:

var el = document.querySelector('div');

// get element content as string
console.log(el.innerHTML)

// append to the element's content
el.innerHTML += '<p>Hello World!</p>';

// prepend to the element's content
el.innerHTML = '<p>Hello World!</p>' + el.innerHTML;

innerHTML is essentially the element's content as a string. Be warned, though: Modifying innerHTML will destroy and rebuild all descendant elements of the container. Event handlers bound to any of the destroyed elements are lost in the process and need to be reattached if required.

Alternatively, it's possible to use DOM methods for creating, inserting, and moving elements:

var el = document.querySelector('div');

// create a p element for inserting in el
var newEl = document.createElement('p');
// use the innerHTML property for inserting HTML content
// or append a textNode to the p element
newEl.appendChild(document.createTextNode('Hello World!'));

// append p as a new child to el
el.appendChild(newEl);

// same result with insertBefore()
el.insertBefore(newEl, null);

// use as second argument the child node you want to insert the new node before
// example: prepend newEl as first child to el
el.insertBefore(newEl, el.childNodes[0] || null);

This approach requires more code, and is in general slower or equally fast as working with innerHTML. However, using DOM methods ensures event handlers bound to the element's content remain intact.

Check out w3schools for some more examples.


Feedback