Changing Content
After you select an element with JavaScript, you can change what it says, update how it looks, or even completely replace parts of the page. JavaScript makes it simple to update content and styles so your pages can be dynamic and interactive.
There are two main ways to change what’s inside an element: textContent
and innerHTML
. They seem similar, but they behave differently.
textContent: The straightforward one
This property lets you get or set the text within a selected element. For example:
<h1>Welcome to my website!</h1>
const heading = document.querySelector('h1');
// Get the current text content
heading.textContent; // Output: Welcome to my website
// Set new text content
heading.textContent = 'Welcome to JSBites!';
This wipes whatever was inside the <h1> and replaces it with plain text. It’s safe, fast, and great.
innerHTML: The powerful (and risky) one
This one lets you include HTML tags as part of the content. It gives you more control.
<div class="box"></div>
const box = document.querySelector('.box');
box.innerHTML = '<strong>Hello</strong>, <em>world</em>!';
Now the box contains bold and italic text. Cool, right? Just be careful not to use innerHTML
with data from users—it can open the door to XSS attacks (aka scary security stuff).
- Use
textContent
when you just need to insert or update plain text. It’s safer and faster. - Use
innerHTML
when you want to inject some HTML structure—like links, bold tags, or icons.