JavaScript code for adding new elements in a dynamic way - GeeksforGeeks

21 Sep, 2021
Javascript is a very important language when it comes to learning how the browser works. Often there are times we would like to add dynamic elements/content to our web pages. This post deals with all of that.
Creation of new element: New elements can be created in JS by using the createElement() method.  
Syntax:
document.createElement("<tagName>");  
// Where <tagName> can be any HTML 
// tagName like div, ul, button, etc.

// newDiv element has been created
For Eg: let newDiv = document.createElement("div");
Once the element has been created, let’s move on to the setting of attributes of the newly created element.
 
Setting the attributes of the created element: Attributes can be set using setAttribute() method.  
The syntax and example are as follows:
Element.setAttribute(name, value);
// Where Element is the name of web element. 
// Here, we have created newDiv.
// Where name is the attribute name and 
// value is the value that needs to be set

For Eg: newDiv.setAttribute("class","container");
Example: Elements can be created based on some event like a click. Here’s an example of how to create elements dynamically with an onclick event. This code can be further made into a todo-list!
HTML
<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8">    <meta http-equiv="X-UA-Compatible" content="IE=edge">    <meta name="viewport" content=        "width=device-width, initial-scale=1.0">      <style>        html,        body {            height: 100%;            width: 100%;        }          .button {            display: flex;            align-items: center;            justify-content: center;        }          .tasks {            display: flex;            justify-content: center;            align-items: center;            flex-direction: column;            margin-top: 20px;        }    </style></head>  <body>    <div class="button">        <button id="addTask">Add task</button>    </div>    <div class="tasks"></div>    <script type="text/javascript">          // Getting the parent element in which        // the new div will be created        let task = document.getElementsByClassName("tasks");          // Getting the addTask button element        let addTask = document.getElementById("addTask");                  // Adding onclick event to the button        addTask.addEventListener('click', function () {                  // Traversing through collection of HTML            // elements (tasks here)            for (let i = 0; i < task.length; i++) {                                  // New div element is created                  let newDiv = document.createElement("div");                                      // Setting the attribute of class type to newDiv                 newDiv.setAttribute("class", "list");                                     // innerText used to write the text in newDiv                 newDiv.innerText = "New Div created";                                       // Finally append the newDiv to the                // parent i.e. tasks                   task[i].append(newDiv);            }        })    </script></body>  </html>
Output:  
Blogathon-2021
CSS-Properties
HTML-Questions
JavaScript-Methods
JavaScript-Questions
Picked
Blogathon
CSS
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install Numpy on MacOS?
Dart - Null Aware Operators
How to Create a Table With Multiple Foreign Keys in SQL?
How to Install Tkinter in Windows?
Format Dates in Flutter
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
How to update Node.js and NPM to next version ?
Types of CSS (Cascading Style Sheet)