Home >Web Front-end >JS Tutorial >How Can JavaScript Change the Text Content of an HTML Element?

How Can JavaScript Change the Text Content of an HTML Element?

DDD
DDDOriginal
2024-12-16 02:39:13271browse

How Can JavaScript Change the Text Content of an HTML Element?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn