How to Change HTML Text Using JavaScript?

Estimated read time 1 min read

To change the text of an HTML element using JavaScript, you can select the element and set its textContent or innerHTML property to the new text. Here’s an example:

// Select the element to be changed
const myElement = document.getElementById('my-element');

// Change the element's text using textContent
myElement.textContent = 'New text content';

// Change the element's text using innerHTML
myElement.innerHTML = '<em>New</em> text <strong>content</strong>';

In this example, getElementById('my-element') selects the element with the ID of “my-element”. The first myElement.textContent example sets the text content of the element to “New text content”, while the second myElement.innerHTML example sets the HTML content of the element to “New text content” with the word “New” italicized and “content” bolded.

Note that when using innerHTML, be careful to avoid injecting unsanitized user input, as this can lead to security vulnerabilities such as cross-site scripting (XSS) attacks. To prevent this, you can use methods like innerText or textContent instead of innerHTML, or sanitize the input using a library or function designed for this purpose.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply