Home >Web Front-end >JS Tutorial >How Can I Safely Change the Text of an HTML Element Using JavaScript?
JavaScript: Modifying Element Text
Changing the text content of an HTML element using JavaScript is a common task. One effective method is to utilize the textContent property.
To modify the text of a element with the ID "myspan", use the following code:
document.getElementById("myspan").textContent = "newtext";
This approach is appropriate for modern browsers. However, some older browsers may not recognize textContent. While using innerHTML may seem tempting, it introduces a potential cross-site scripting (XSS) vulnerability, especially if the new content originates from user input.
Therefore, for secure and cross-browser compatibility, it's recommended to use textContent when modifying element text via JavaScript.
The above is the detailed content of How Can I Safely Change the Text of an HTML Element Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!