To append HTML content to the <body>
element in JavaScript, you can use the insertAdjacentHTML
method or the appendChild
method. Here are examples of both approaches:
Using insertAdjacentHTML
:
// HTML content to append
var htmlContent = '<div>Hello, World!</div>';
// Append the HTML content to the body
document.body.insertAdjacentHTML('beforeend', htmlContent);
Using appendChild
:
// HTML content to append
var htmlContent = '<div>Hello, World!</div>';
// Create a new element
var divElement = document.createElement('div');
divElement.innerHTML = htmlContent;
// Append the new element to the body
document.body.appendChild(divElement);
Both approaches achieve the same result of appending HTML content to the <body>
element. Choose the method that suits your needs and coding style.
JavaScript append HTML to body example
Simple example code.
<!DOCTYPE html>
<html>
<head>
<script>
window.addEventListener('DOMContentLoaded', function() {
// HTML content to append
var htmlContent = '<div>Hello, World!</div>';
// Append the HTML content to the body
document.body.innerHTML += htmlContent;
});
</script>
</head>
<body>
<h1>Original Content</h1>
<p>This is the existing content of the body.</p>
</body>
</html>
Output:
When the page loads, the JavaScript code executes, appending the new <div>
element to the existing content in the <body>
. The result is that “Hello, World!” is displayed as part of the page content.
Do comment if you have any doubts or suggestions on this JS HTML code.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version