Whenever we work with JavaScript we may need to dynamically create new elements like div, buttons, etc.

So, in this article, we will discuss how to dynamically create HTML element (div, button, paragraph, heading etc.) in JavaScript.

How to dynamically create div element? #

To create a new element (div) , we will use the createElement() method.

const newDiv = document.createElement('div');
      newDiv.innerText = 'New Div Element.';
      document.body.appendChild(newDiv);

How to add onclick attribute to be the div element. #

We can add an attribute to the created div element using the setAttribute() method.

const newDiv = document.createElement('div');
      newDiv.setAttribute("onclick","alert('hi')");