JS Learning

DOM Manipulation

Lesson Progress0%

Section 2 of 4

Modifying Elements

Modifying Elements

Topic Overview

Take your time to understand each concept. Practice with the examples below!

Once you've selected an element, you can change almost anything about it! This is where your web pages come alive.

Changing Content:

  • textContent - Change just the text (safe from HTML)
const title = document.getElementById('title');
title.textContent = "New Title Text";
  • innerHTML - Change HTML inside an element
const div = document.querySelector('.content');
div.innerHTML = "<p>New paragraph</p>";

Working with CSS Classes:

  • classList.add() - Add a class
element.classList.add('active');
  • classList.remove() - Remove a class
element.classList.remove('hidden');
  • classList.toggle() - Switch on/off
element.classList.toggle('dark-mode');

Changing Styles Directly:

  • element.style.property = value
button.style.backgroundColor = "blue";
button.style.fontSize = "18px";
button.style.display = "none"; // Hide element

Changing Attributes:

  • setAttribute() - Change any HTML attribute
image.setAttribute('src', 'new-image.jpg');
link.setAttribute('href', 'https://example.com');

Practical examples:

  • Show/hide elements
  • Change colors on hover
  • Update text based on user actions
  • Switch between light/dark themes
  • Display error or success messages