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
Release: 2024-12-16 02:39:13
Original
269 people have browsed it

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>
Copy after login

How can JavaScript be used to replace "hereismytext" with "newtext"?

Answer:

For Modern Browsers:

document.getElementById("myspan").textContent = "newtext";
Copy after login

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";
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template