How to Alter Element Text with JavaScript
Question:
Consider a span element with the ID "myspan":
<span>
How can JavaScript be used to replace "hereismytext" with "newtext"?
Answer:
For Modern Browsers:
document.getElementById("myspan").textContent = "newtext";
For Older Browsers (Caution):
While older browsers may not support textContent, it is crucial to avoid using innerHTML due to its potential introduction of XSS vulnerabilities if the new text originates from user input.
//POSSIBLY INSECURE IF NEWTEXT BECOMES A VARIABLE!! document.getElementById("myspan").innerHTML = "newtext";
The above is the detailed content of How Can JavaScript Change the Text Content of an HTML Element?. For more information, please follow other related articles on the PHP Chinese website!