#javascript #tutorial #beginner

Day 5: DOM Manipulation Basics

Day 5: The DOM (Document Object Model)

The DOM is the bridge between your JavaScript code and the HTML that the user sees. It represents the page as a tree structure.

1. Selecting Elements

Before you can change an element, you must find it.

// New Way (Recommend)
const title = document.querySelector('h1'); // Selects the first <h1>
const button = document.querySelector('#myButton'); // Selects id="myButton"
const items = document.querySelectorAll('.item'); // Selects ALL class="item"

// Old Way (Still common)
const box = document.getElementById('box');

2. Changing Content

const heading = document.querySelector('h1');

// Change text
heading.innerText = "Welcome to JavaScript!";

// Change HTML (be careful of security!)
heading.innerHTML = "Welcome to <span>JS</span>";

3. Changing Styles

You can manipulate CSS directly via the style property.

const box = document.querySelector('.box');

box.style.backgroundColor = "blue";
box.style.fontSize = "20px"; // Note: camelCase (font-size -> fontSize)
box.style.display = "none"; // Hides element

4. Class Manipulation (Best Practice)

Instead of changing individual styles, it’s cleaner to toggle CSS classes.

const box = document.querySelector('.box');

box.classList.add('active');
box.classList.remove('hidden');
box.classList.toggle('dark-mode');

Homework for Day 5:

  1. Create an HTML file with a <p id="message">Hello</p> and a <button id="btn">Click me</button>.
  2. In your JS, select both elements.
  3. Change the text of the paragraph to “Goodbye” (you can just run this code immediately for now, we learn click events tomorrow!).

Day 6: Events & Interactivity!