How to modify the text content of an HTML element using JavaScript?

To modify the text content of an HTML element using JavaScript, you can use the textContent property. Here are the steps to modify the text content:

  1. First, select the HTML element whose text content you want to modify. You can use various methods of selecting elements such as getElementById, querySelector, etc.

  2. Once you have selected the element, you can access and modify its text content using the textContent property.

  3. Assign the desired text content to the textContent property. For example, if you want to change the text content to "Hello, World!", you can use element.textContent = "Hello, World!";

Here is an example that demonstrates how to modify the text content of a paragraph with id "myParagraph":

<!DOCTYPE html> <html> <body> <p id="myParagraph">Hello</p> <script> // Select the paragraph element using getElementById var paragraph = document.getElementById("myParagraph"); // Modify the text content to "Hello, World!" paragraph.textContent = "Hello, World!"; </script> </body> </html>

After executing the JavaScript code, the paragraph element will be updated with the new text content of "Hello, World!".