JavaScript Answers

How to insert HTML elements with JavaScript?

Spread the love

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">
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Insert HTML Elements with JavaScript</title>

  <div id="container">
    <!-- Existing content -->

    // 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 = "";
    newLink.textContent = "Click here";

    // Get the container element
    var container = document.getElementById("container");

    // Append the new elements to the container
    container.appendChild(document.createElement("br")); // Add a line break


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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *