How do you change the text inside an element in JavaScript?
In JavaScript, you can change the text inside an HTML element by manipulating its innerHTML or textContent property. Here's how:
1. Access the element in the DOM
You can use methods like document.getElementById(), document.getElementsByClassName(), document.querySelector(), or document.querySelectorAll() to select the element that you want to change.
For example, let's say we have the following HTML code:
<div class="my-div">This is an element.</div>
To select the above div element with the class "my-div", we can use:
const myDiv = document.querySelector('.my-div');
2. Change the innerHTML or textContent property:
Once you have selected the element, you can use its innerHTML or textContent property to update its text.
The innerHTML property sets or returns the HTML content (including any HTML tags) inside an element. For example, if you want to change the text into a link, you can use :
myDiv.innerHTML = "<a href='https://www.example.com'>Click Here</a>";
The textContent property sets or returns the text content inside an element, stripping any HTML tags. If you just want to replace the text in the div element, you can use:
myDiv.textContent = "New Text";
Note that using innerHTML can be potentially dangerous because it allows for the injection of malicious code. Use it with caution, and consider sanitizing user input before using it in innerHTML.