We can insert HTML elements into a document using JavaScript by creating the elements using the document.createElement()
method, modifying their attributes and content as needed, and then appending them to the desired location in the document using methods like appendChild()
or insertBefore()
.
For example we write:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Insert HTML Elements with JavaScript</title>
</head>
<body>
<div id="container">
<!-- Existing content -->
</div>
<script>
// Create a new paragraph element
var newParagraph = document.createElement("p");
// Set the text content of the paragraph
newParagraph.textContent = "This is a new paragraph.";
// Create a new link element
var newLink = document.createElement("a");
// Set attributes and content for the link
newLink.href = "https://www.example.com";
newLink.textContent = "Click here";
// Get the container element
var container = document.getElementById("container");
// Append the new elements to the container
container.appendChild(newParagraph);
container.appendChild(document.createElement("br")); // Add a line break
container.appendChild(newLink);
</script>
</body>
</html>
In this example, a new paragraph (<p>
) element and a new link (<a>
) element are created using document.createElement()
.
Their attributes and content are set accordingly.
Then, the container element (an existing <div>
with the ID “container”) is selected using document.getElementById()
, and the new elements are appended to it using the appendChild()
method.