How to create an HTML element dynamically using JavaScript

Hello Developers,

A web page is consist of many HTML elements. HTML element can be added in HTML file very easily, but there are times when we need to add those HTML elemetns dymanically. For example consider a blog page, where at the botton a button is given to add comments. In such case when user clicks on the button it creates a new comment box for user and adds in the exisitng web page.

so in this article we will how to add HTML elemetns dymanically using javascript.

Create the Element:

  • Use the document.createElement method to create a new HTML element. Specify the type of element you want to create (e.g., div, p, span).

  • append to the Document:

    • Use parentElement.appendChild or parentElement.insertBefore to add the newly created element to the desired location in the document.

Basic steps includes

  1. create and html file

  2. write inline script or link a javascript file to this html file

  3. write code to add new html element using document.createElement

  4. add this newly created element to web page by using any of the methods .append/.prepend/.appendChild/insertBefore

Example

<!DOCTYPE HTML>

<HTML>

<head></head>

<body>

<script>

// Step 1: Create a new div element

var newDiv = document.createElement('div');

// Step 2 (Optional): Set attributes for the

new div newDiv.setAttribute('id', 'myDynamicDiv'); newDiv.setAttribute('class', 'dynamic-class');

// Step 3 (Optional): Set content for the new div newDiv.textContent = 'This is a dynamically created div!';

// Step 4: Append the new div to the body of the document document.body.appendChild(newDiv);

</script>

</body>

</HTML>