This post will discuss how to insert HTML into a div in JavaScript and jQuery.

1. Using jQuery

With jQuery, you can use the .append() method to insert the specified HTML as the last child of the div container.

JS


HTML



Edit in JSFiddle

 
To insert the specified content as the first child of the div container, consider using the .prepend() method instead.

JS


HTML



Edit in JSFiddle

2. Using JavaScript

In plain JavaScript, the innerHTML property is often used to replace the contents of an element. To insert the HTML into a container rather than replacing its entire contents, you can use the += operator, as shown below:

JS


HTML



Edit in JSFiddle

 
Instead of directly changing the innerHTML, you should use the appendChild() method.

JS


HTML



Edit in JSFiddle

 
Alternatively, JavaScript has a native method insertAdjacentHTML() to insert the HTML into the document. It takes the position relative to the element, which can be either:

  • 'beforebegin': Before the element itself.
  • 'afterbegin': Just inside the element, before its first child.
  • 'beforeend': Just inside the element, after its last child.
  • 'afterend': After the element itself.

JS


HTML



Edit in JSFiddle

That’s all about inserting HTML into a div in JavaScript and jQuery.