Skip to content

JavaScript append HTML to div

  • by

Appending HTML content to a div element using JavaScript is a common task in web development. There are a few different ways to achieve this, but two common methods are using the innerHTML property and the insertAdjacentHTML() method.

Using the innerHTML property, you can set the entire content of a div element, including any existing content, by assigning a string of HTML to the innerHTML property. To append new content to an existing div, you can concatenate the new HTML content to the existing innerHTML using the += operator.

var html = "<p>This is some new HTML content!</p>";
document.getElementById("myDiv").innerHTML += html;

Using the insertAdjacentHTML() method, you can insert HTML content at a specific position in relation to the div element. This method takes two arguments: the position and the HTML content to insert. The available positions are beforebegin, afterbegin, beforeend, and afterend.

var html = "<p>This is some new HTML content!</p>";
document.getElementById("myDiv").insertAdjacentHTML("beforeend", html);

JavaScript append HTML to div example

Simple example code.

To append HTML to a div element using JavaScript, you can use the innerHTML property of the div.

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Append HTML to Div</title>
</head>
<body>

  <div id="myDiv">
    <!-- Existing content of the div goes here -->
  </div>

  <script>
    var html = "<p>This is some new HTML content!</p>";
    document.getElementById("myDiv").innerHTML += html;
  </script>

</body>
</html>

Use the insertAdjacentHTML() method to append HTML content after the end of a div element:

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Append HTML to Div</title>
</head>
<body>

  <div id="myDiv">
    <!-- Existing content of the div goes here -->
  </div>

  <script>
    var html = "<p>This is some new HTML content!</p>";
    document.getElementById("myDiv").insertAdjacentHTML("beforeend", html);
  </script>

</body>
</html>

Output:

JavaScript append HTML to div

Comment if you have any doubts or suggestions on this JS HTML topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading