Skip to content

JavaScript append HTML

  • by

JavaScript append HTML technique used in web development that allows dynamically adding or inserting HTML content into an existing web page. By leveraging methods such as innerHTML, insertAdjacentHTML(), or DOM manipulation, developers can append HTML elements, paragraphs, images, or any other desired content to specific sections of a webpage.

Here are a few commonly used methods to append HTML using JavaScript:

innerHTML:

var container = document.getElementById("container");
container.innerHTML += "<p>This is some appended HTML content.</p>";

insertAdjacentHTML():

var container = document.getElementById("container");
container.insertAdjacentHTML("beforeend", "<p>This is some appended HTML content.</p>");

Using createElement() and appendChild():

var container = document.getElementById("container");
var paragraph = document.createElement("p");
paragraph.textContent = "This is some appended HTML content.";
container.appendChild(paragraph);

Using document.createRange() and insertNode():

var container = document.getElementById("container");
var range = document.createRange();
range.setStart(container, container.childNodes.length);
var fragment = range.createContextualFragment("<p>This is some appended HTML content.</p>");
container.appendChild(fragment);

JavaScript append HTML example

Simple example code that demonstrates how to append HTML content using JavaScript:

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Append HTML Example</title>
</head>
<body>
  <div id="container">
    <h2>Original Content</h2>
  </div>

  <button onclick="appendHTML()">Append HTML</button>

  <script>
    function appendHTML() {
      var container = document.getElementById("container");
      var htmlContent = "<p>This is some appended HTML content.</p>";
      container.innerHTML += htmlContent;
    }
  </script>
</body>
</html>

Output:

JavaScript append HTML

When the button is clicked, the appendHTML() function is executed. It retrieves the reference to the container element using getElementById(). Then, it creates a string htmlContent that contains the HTML content we want to append.

Comment if you have any doubts or suggestions on this Js Append 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