Signup/Sign In

How to change the text of a span element using JavaScript?

Answer: Using textContent property

The textContent property is used to set and return the text content of the specified node and all its descendants.

To get the content of the span element uses the textContent property along with the getElementById() method. We can also get the content of the span element using the innerText property. Both the properties are similar, but there are some differences between them these are:

  • The textContent property returns the content of all elements while the innerText property also returns the content of all elements except <script> and <style> tag.
  • The innerText property does not display the text that is hidden using CSS properties.

Using these properties, we can remove any number of child nodes. We can also replace the text inside the node with a single text node containing the specified node.

Example: Using textContent Property

In the given example, we have used the textContent property to change the text of the span element.

<!DOCTYPE html>
<html lang="en">
<head>
	<title>Change the text of a span element</title>
</head>
<body>
	<span id="myspan">Hello World</span>
	<script>
		document.getElementById("myspan").textContent="Welcome to Studytonight";
	</script>
</body>
</html>

Output


Welcome to Studytonight

Using innerText Property

We can also change the existing text of the span element using the JavaScript innerText property. This property sets or returns the text content of the specified element or its descendants.

Example: Using innerText property

In this example, we have used the innerText property to change the content of the span element.

<!DOCTYPE html>
<html lang="en">
<head>
	<title>Change the text of a span element</title>
</head>
<body>
	<span id="myspan">Hello World</span>
	<script>
    	document.getElementById("myspan").innerText="Welcome to Studytonight";  
	</script>
</body>
</html>

Output


Welcome to Studytonight

Conclusion

Here, we have discussed how to change the text of a span element using JavaScript. We can change the text of a span element using textContent property and innerText property. Both the properties enable us to change the existing text content of the span element dynamically.



About the author: