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
orparentElement.insertBefore
to add the newly created element to the desired location in the document.
- Use
Basic steps includes
create and html file
write inline script or link a javascript file to this html file
write code to add new html element using
document.createElement
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>