JavaScript Insert Span Into DIV Element (Dynamically with JS)

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:

JavaScript insert span into div element.

<!DOCTYPE html>
<title>Add span into div element with Javascript - Coding Is Easy</title>

<div id="codingIsEasy">
<p>Code Made Easy</p>

  var newSpan = document.createElement('span');
  newSpan.textContent = "Hello! I am added Dynamically";



Adding span dynamically to div with JS.

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.


Leave a Comment