Creation of new element: New elements can be created in JS by using the createElement() method.
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!