How to add HTML elements dynamically using JavaScript?

JavascriptWeb DevelopmentFront End Technology

In this article, we will be exploring how to add HTML elements dynamically so that they could change the view component. Also not just an HTML element, we can also add CSS properties to HTML elements with the help of JavaScript. In this article, we will be using a button to facilitate the addition of an HTML element in the already built template.

Approach

  • We will create a Simple HTML page with some components defined.

  • Once the page is created we will be writing some outer HTML and adding a button to it so that we could add this HTML when a user clicks on the button.

  • This HTML is dynamically added one by one in a list format.

  • We are going to write a JavaScript function attached to the onclick event. This event will listen for the trigger and add the desired HTML to the page.

  • We will also create a callback that will tell us if the HTML element was successfully added or not.

Example

In the below example, we are going to add an HTML element with the click of a button. Whenever the button will be clicked we will be adding an HTML element to the already created page.

# index.html

<!DOCTYPE html>
<html>
<head>
   <title>Adding HTML elements dynamically</title>
   <style>
      h1 {
         color: green;
         display: flex;
         justify-content: center;
      }
      #mybutton {
         display: block;
         margin: 0 auto;
      }
      #innerdiv {
         display: flex;
         flex-direction: column;
         justify-content: center;
         align-items: center;
      }
   </style>
</head>
<body>
   <h1>
      Welcome To Tutorials Point
   </h1>
   <div id="innerdiv"></div>
   <button id="mybutton">
      Click to Add HTML element
   </button>
   <script>
      document.getElementById("mybutton").
      addEventListener("click", function () {
         document.getElementById("innerdiv").innerHTML += "<h3>Hello User</h3><p>Start your learning journey today.</p>";
      });
   </script>
</body>
</html>

Output

The above program will produce the following result −

Click the “Click to Add HTML element” button, it will add an element to the page −

raja
Updated on 22-Apr-2022 12:31:57

Advertisements