There are a couple of ways that we can change the text in a span using JavaScript. The first way we can do this is with the innerHTML property:
document.getElementById("div1").innerHTML = "Changing this text in #div1";
Let’s say we have the following HTML:
The innerHTML property gives us the ability to insert HTML into our div and change the HTML that was in there. By doing this we can change the span text that was in there too.
So to change the span text in the div above from “November” to “December” we can use the following code:
var currDiv = document.getElementById("div1");
currDiv.innerHTML = "Today is December 3rd.";
Which would result in:
Changing the Text in a Span with JavaScript using the Id and TextContent property
Another way we can change the text of a span using JavaScript is to give the span an id, and target the id with the getElementById method.
Let’s say we have the following HTML:
We can give the span an id of “span1”.
We can then target the “span1” id and change the text of it using the textContent property. Here is the code:
function clickFunction() {
var currSpan = document.getElementById("span1");
currSpan.textContent = "December";
}
Which would result in:
Hopefully this article has been useful for you to understand how to change text in a span using Javascript.