JavaScript change span text | set value in span example

How do I change the text of a span element using JavaScript?

Use textContent with getElementById method to get span element text in JavaScript. You can also innerHTML but it’s not recommended to use as it introduces an XSS vulnerability when the new text is user input.

For modern browsers you should use:


Example code of How to JavaScript change span text

HTML example code set value in span using JavaScript.

<!DOCTYPE html>
    <span id="span1">Another Text</span>

        document.getElementById("span1").textContent="New Text";



JavaScript change span text

Do comment if you have other example or doubts or suggestion on this topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.