Categories
JavaScript Answers

How to add text into span after calling document.createElement(“span”) with JavaScript?

Spread the love

Sometimes, we want to add text into span after calling document.createElement("span") with JavaScript.

In this article, we’ll look at how to add text into span after calling document.createElement("span") with JavaScript.

How to add text into span after calling document.createElement("span") with JavaScript?

To add text into span after calling document.createElement("span"), we can set the textContent property of the span element to the text we want to see.

For instance, we write:

const closeSpan = document.createElement("span");
closeSpan.textContent = "Close";
document.body.appendChild(closeSpan)

We create the span with:

const closeSpan = document.createElement("span");

Then we set the text content of the span with:

closeSpan.textContent = "Close";

Finally, we attach the span to the body as its child with:

document.body.appendChild(closeSpan)

Conclusion

To add text into span after calling document.createElement("span"), we can set the textContent property of the span element to the text we want to see.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *