Changing Content and Styles

After you select an element with JavaScript, the real fun begins — 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.

textContent

The textContent property lets you change just the text inside an element. It's a safe and quick way to update what the user sees.

Example:

javascript
1
2
          const heading = document.querySelector('h1');
heading.textContent = 'Welcome to My Website!';
        

innerHTML

If you want to change both the text and include HTML (like adding a bold word or a link), you can use innerHTML:

javascript
1
2
          const paragraph = document.querySelector('p');
paragraph.innerHTML = 'Click <a href="#">here</a> to learn more.';
        

Be careful with innerHTML though — if you use it with user input, it can lead to security risks like XSS (cross-site scripting).

.style

To change the style of an element directly, you can use the .style property:

javascript
1
2
3
          const button = document.querySelector('button');
button.style.backgroundColor = 'blue';
button.style.color = 'white';
        

This method lets you quickly apply styles, but for bigger projects, it’s better to use CSS classes instead.

Inline styles vs CSS classes

When you change styles with .style, you’re adding inline styles directly to the element. This can make your HTML messy and harder to manage later.

Example of an inline style:

javascript
1
          <button style="background-color: blue; color: white;">Click Me</button>
        

A better way for most projects is to define styles in your CSS file and then use JavaScript to add or remove CSS classes.

Example:

css
1
2
3
4
5
          /* In your CSS file */
.highlight {
  background-color: yellow;
  font-weight: bold;
}
        
javascript
1
2
3
          // In your JavaScript
const text = document.querySelector('p');
text.classList.add('highlight');
        

Using classes keeps your code cleaner, easier to read, and more scalable as your project grows.

Removing and toggling classes

JavaScript also lets you easily remove a class with classList.remove() or toggle it with classList.toggle():

javascript
1
2
          text.classList.remove('highlight');
text.classList.toggle('highlight');
        

This is super useful for adding effects like dark mode, showing/hiding menus, or activating animations.