As we all know, we can create elements using HTML and CSS but there is another way also to dynamically create elements using JavaScript. So, today we will learn about how to create elements using JavaScript dynamically.
Here’s a quick example that creates a span, adds some text to it and appends it as the last element in the div tag:
Table of Contents
JavaScript insert span into div element.
<!DOCTYPE html>
<html>
<head>
<title>Add span into div element with Javascript - Coding Is Easy</title>
</head>
<body>
<div id="codingIsEasy">
<p>Code Made Easy</p>
</div>
<script>
var newSpan = document.createElement('span');
newSpan.textContent = "Hello! I am added Dynamically";
document.getElementById("codingIsEasy").appendChild(newSpan);
</script>
</body>
</html>
Output

Basic Explanation:
To create the element we need to pass an HTML tag name to document.createElement().
In the second step, we provide the text, so that the textContent gets modified. Lastly, the appendChild() method is used to add the element to the div tag based on the ID.
Remember, the setAttribute property can be used to add a class name attribute.
Example: newSpan.setAttribute(‘class’, ‘note’);
More about it:
You can also consider to use another node properties like innerText & innerHTML which are supported by almost all the browsers.
In case, the user’s browser doesn’t support textContent we can add the condition to render it with innerText.
var span = document.createElement('span');
if (span.textContent) {
span.textContent = "Hello!";} else if (span.innerText) {
span.innerText = "Hello!";
}
Removing an element with JavaScript
We can also remove elements with JavaScript. To remove an element we can use removeChild() method. We need to pass the child element of a parent as an argument here.
Syntax:
div.parentNode.removeChild(div);