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:
document.getElementById("spanId").textContent="newtext";
Example code of How to JavaScript change span text
HTML example code set value in span using JavaScript.
<!DOCTYPE html>
<html>
<body>
<span id="span1">Another Text</span>
<script>
document.getElementById("span1").textContent="New Text";
</script>
</body>
</html>
Output:
Do comment if you have other examples or doubts or suggestions 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