Lesson 4 โ€ข Beginner

    DOM Manipulation ๐ŸŽจ

    Learn how to interact with and modify HTML elements using JavaScript โ€” bring your webpages to life with dynamic content, styles, and interactivity.

    What You'll Learn in This Lesson

    • โœ“What the DOM is and how it works
    • โœ“Select elements with querySelector
    • โœ“Change text content and innerHTML
    • โœ“Modify styles and CSS classes dynamically
    • โœ“Create, append, and remove elements
    • โœ“Navigate the DOM tree with parent/child relationships

    ๐Ÿ’ก Running Code Locally: While this online editor runs real JavaScript, some advanced examples may have limitations. For the best experience:

    • Download Node.js to run JavaScript on your computer
    • Use your browser's Developer Console (Press F12) to test code snippets
    • Create a .html file with <script> tags and open it in your browser

    ๐ŸŒณ What is the DOM?

    The Document Object Model (DOM) is a programming interface for web documents. It represents your HTML page as a tree of objects that JavaScript can interact with.

    Think of the DOM as a live representation of your webpage that you can read and modify in real-time.

    ๐Ÿง  Real-World Analogy:

    Imagine your HTML is like a blueprint of a house. The DOM is the actual house that's been built from that blueprint. With JavaScript, you can walk through that house, change the paint colors, move furniture around, or even add new rooms โ€” all while people are inside!

    Everything on a webpage โ€” every paragraph, image, button, and div โ€” is represented as an object in the DOM tree.

    ๐ŸŽฏ Why DOM Manipulation Matters

    Without the DOM, web pages would be static and boring. DOM manipulation is what makes the web interactive:

    • โœ“Update content without reloading the page (like social media feeds)
    • โœ“Respond to user actions (clicks, typing, scrolling)
    • โœ“Create animations and visual effects
    • โœ“Build dynamic forms with validation
    • โœ“Show/hide elements based on conditions

    ๐Ÿ” Selecting Elements โ€” Finding What You Need

    Before you can manipulate an element, you need to select it. JavaScript gives you several powerful methods to find elements in the DOM.

    ๐Ÿ“Œ Method 1: getElementById

    The most direct way to select an element โ€” by its unique id attribute.

    const header = document.getElementById('main-header');
    console.log(header); // Returns the element with id="main-header"
    ๐Ÿ’ก Pro Tip: IDs should be unique on a page, so this method returns one element (or null if not found).

    ๐Ÿ“Œ Method 2: getElementsByClassName

    Select all elements with a specific class name. Returns an HTMLCollection (array-like object).

    const buttons = document.getElementsByClassName('btn');
    console.log(buttons[0]); // First button
    console.log(buttons.length); // Number of buttons

    ๐Ÿ“Œ Method 3: querySelector (Modern & Recommended)

    The most versatile method โ€” uses CSS selectors to find elements. Returns the first match.

    // Select by class
    const container = document.querySelector('.container');
    
    // Select by ID
    const header = document.querySelector('#main-header');
    
    // Select by tag
    const firstParagraph = document.querySelector('p');
    
    // Advanced: select nested elements
    const submitBtn = document.querySelector('form .submit-btn');

    ๐Ÿ“Œ Method 4: querySelectorAll

    Like querySelector, but returns all matching elements as a NodeList.

    const allButtons = document.querySelectorAll('.btn');
    
    // Loop through all buttons
    allButtons.forEach(button => {
      console.log(button.textContent);
    });

    โœ… Best Practice:

    Use querySelector and querySelectorAll for modern projects. They're more flexible and work just like CSS selectors you already know!

    โœ๏ธ Changing Content โ€” textContent vs innerHTML

    Once you've selected an element, you can change what's inside it.

    ๐Ÿ”ค Using textContent (Safer)

    Changes the plain text inside an element. HTML tags are treated as text, not rendered.

    const heading = document.querySelector('h1');
    heading.textContent = "Welcome to my website!";
    
    // HTML tags are escaped (safe from XSS attacks)
    heading.textContent = "<script>alert('hack')</script>"; 
    // Displays as text, doesn't run code โœ…

    ๐Ÿ—๏ธ Using innerHTML (More Powerful)

    Changes the HTML content inside an element. Tags are parsed and rendered.

    const container = document.querySelector('.container');
    container.innerHTML = "<h2>New Title</h2><p>Some text</p>";
    
    // Can add multiple elements at once
    container.innerHTML = `
      <div class="card">
        <h3>Card Title</h3>
        <p>Card content</p>
      </div>
    `;

    โš ๏ธ Security Warning:

    Be careful with innerHTML when inserting user-provided content! It can expose your site to XSS (Cross-Site Scripting) attacks. Use textContent for user input, or sanitize the HTML first.

    ๐Ÿ“ Example: Updating a Counter

    const counter = document.querySelector('#counter');
    let count = 0;
    
    setInterval(() => {
      count++;
      counter.textContent = `Count: ${count}`;
    }, 1000); // Updates every second

    ๐ŸŽจ Changing Styles โ€” Making Things Beautiful

    You can modify CSS styles directly using JavaScript's style property.

    ๐Ÿ–Œ๏ธ Basic Styling

    const box = document.querySelector('.box');
    
    // Change individual properties
    box.style.color = "blue";
    box.style.backgroundColor = "#f0f0f0";
    box.style.fontSize = "20px";
    box.style.padding = "15px";
    box.style.borderRadius = "8px";
    ๐Ÿ’ก Notice: CSS properties with hyphens (like background-color) become camelCase in JavaScript (backgroundColor).

    ๐ŸŽญ Multiple Styles at Once

    const element = document.querySelector('.element');
    
    // Using cssText (overwrites existing styles)
    element.style.cssText = `
      color: white;
      background-color: #333;
      padding: 20px;
      border-radius: 10px;
    `;

    ๐Ÿ”„ Example: Theme Switcher

    const body = document.body;
    const themeBtn = document.querySelector('#theme-toggle');
    
    themeBtn.addEventListener('click', () => {
      if (body.style.backgroundColor === 'white' || !body.style.backgroundColor) {
        // Dark mode
        body.style.backgroundColor = '#1a1a1a';
        body.style.color = '#ffffff';
      } else {
        // Light mode
        body.style.backgroundColor = 'white';
        body.style.color = '#000000';
      }
    });

    โœ… Best Practice:

    For complex styling, it's better to add/remove CSS classes rather than inline styles. This keeps your styling logic in CSS where it belongs!

    ๐Ÿท๏ธ Working with Classes โ€” The Professional Way

    The classList API is the modern, clean way to manage CSS classes on elements.

    โž• Adding Classes

    const button = document.querySelector('.btn');
    
    // Add a single class
    button.classList.add('active');
    
    // Add multiple classes
    button.classList.add('primary', 'large', 'animated');

    โž– Removing Classes

    // Remove a single class
    button.classList.remove('active');
    
    // Remove multiple classes
    button.classList.remove('large', 'animated');

    ๐Ÿ”„ Toggling Classes

    The most useful method โ€” adds the class if it's not there, removes it if it is.

    const menu = document.querySelector('.menu');
    const toggleBtn = document.querySelector('#menu-toggle');
    
    toggleBtn.addEventListener('click', () => {
      menu.classList.toggle('open'); // Switches between open/closed
    });

    โœ… Checking if a Class Exists

    if (element.classList.contains('active')) {
      console.log('Element is active!');
    }

    ๐Ÿ“ Real-World Example: Tabs

    const tabs = document.querySelectorAll('.tab');
    
    tabs.forEach(tab => {
      tab.addEventListener('click', () => {
        // Remove 'active' from all tabs
        tabs.forEach(t => t.classList.remove('active'));
        
        // Add 'active' to clicked tab
        tab.classList.add('active');
      });
    });
    ๐Ÿ’ก Why classList is better than className:
    • โ€ข No need to manually parse/split strings
    • โ€ข Prevents accidentally removing other classes
    • โ€ข More readable and maintainable code

    ๐Ÿ—๏ธ Creating & Adding Elements โ€” Build on the Fly

    JavaScript lets you create brand new HTML elements and insert them into your page dynamically.

    ๐Ÿ†• Creating Elements

    // Step 1: Create the element
    const newDiv = document.createElement('div');
    
    // Step 2: Add content
    newDiv.textContent = "I'm a new div!";
    
    // Step 3: Add styling/classes
    newDiv.classList.add('card');
    newDiv.style.padding = '20px';
    
    // Step 4: Add to the page
    document.body.appendChild(newDiv);

    ๐Ÿ“ฆ Inserting Elements โ€” Different Ways

    const container = document.querySelector('.container');
    const newElement = document.createElement('p');
    newElement.textContent = "New paragraph";
    
    // Method 1: Add as last child
    container.appendChild(newElement);
    
    // Method 2: Add as first child
    container.insertBefore(newElement, container.firstChild);
    
    // Method 3: Modern - insertAdjacentElement
    container.insertAdjacentElement('afterbegin', newElement); // Start
    container.insertAdjacentElement('beforeend', newElement);  // End
    container.insertAdjacentElement('beforebegin', newElement); // Before container
    container.insertAdjacentElement('afterend', newElement);    // After container

    ๐Ÿ—‘๏ธ Removing Elements

    const element = document.querySelector('.remove-me');
    
    // Modern way
    element.remove();
    
    // Old way (still works)
    element.parentNode.removeChild(element);

    ๐Ÿ“‹ Example: To-Do List

    const todoList = document.querySelector('#todo-list');
    const addButton = document.querySelector('#add-todo');
    const input = document.querySelector('#todo-input');
    
    addButton.addEventListener('click', () => {
      // Create new list item
      const li = document.createElement('li');
      li.textContent = input.value;
      li.classList.add('todo-item');
      
      // Add delete button
      const deleteBtn = document.createElement('button');
      deleteBtn.textContent = 'ร—';
      deleteBtn.addEventListener('click', () => li.remove());
      
      li.appendChild(deleteBtn);
      todoList.appendChild(li);
      
      // Clear input
      input.value = '';
    });

    ๐Ÿ”ง Working with Attributes โ€” The Details

    Attributes are the properties you set in HTML tags, like id, src, href, data-*, etc.

    ๐ŸŽฏ Getting Attributes

    const link = document.querySelector('a');
    const img = document.querySelector('img');
    
    // Get attribute values
    console.log(link.getAttribute('href'));
    console.log(img.getAttribute('src'));
    console.log(img.getAttribute('alt'));

    โœ๏ธ Setting Attributes

    const button = document.querySelector('button');
    
    // Set attributes
    button.setAttribute('disabled', 'true');
    button.setAttribute('aria-label', 'Submit form');
    button.setAttribute('data-action', 'submit');

    ๐Ÿ—‘๏ธ Removing Attributes

    button.removeAttribute('disabled');

    ๐Ÿ“Š Data Attributes (data-*)

    Custom attributes that start with data- are perfect for storing extra information.

    // HTML: <div id="user" data-id="123" data-role="admin"></div>
    
    const user = document.querySelector('#user');
    
    // Access via dataset
    console.log(user.dataset.id);    // "123"
    console.log(user.dataset.role);  // "admin"
    
    // Set new data attribute
    user.dataset.status = "active";
    // Creates: data-status="active"

    ๐Ÿšซ Common Mistakes to Avoid

    โŒ Mistake 1: Selecting Before DOM is Ready

    // โŒ BAD - Script runs before HTML loads
    const button = document.querySelector('.btn'); // null!
    button.addEventListener('click', ...); // Error!
    
    // โœ… GOOD - Wait for DOM to load
    document.addEventListener('DOMContentLoaded', () => {
      const button = document.querySelector('.btn');
      button.addEventListener('click', ...);
    });

    โŒ Mistake 2: Not Checking if Element Exists

    // โŒ BAD - Assumes element exists
    const header = document.querySelector('.header');
    header.textContent = "New title"; // Error if null!
    
    // โœ… GOOD - Check first
    const header = document.querySelector('.header');
    if (header) {
      header.textContent = "New title";
    }

    โŒ Mistake 3: Using innerHTML with User Input

    // โŒ BAD - XSS vulnerability
    const userInput = "<script>alert('hacked')</script>";
    element.innerHTML = userInput; // Script runs!
    
    // โœ… GOOD - Use textContent for user input
    element.textContent = userInput; // Safe, displays as text

    โŒ Mistake 4: Modifying DOM in a Loop (Slow)

    // โŒ BAD - Multiple reflows
    for (let i = 0; i < 1000; i++) {
      const div = document.createElement('div');
      div.textContent = i;
      document.body.appendChild(div); // Triggers reflow each time
    }
    
    // โœ… GOOD - Build first, append once
    const fragment = document.createDocumentFragment();
    for (let i = 0; i < 1000; i++) {
      const div = document.createElement('div');
      div.textContent = i;
      fragment.appendChild(div);
    }
    document.body.appendChild(fragment); // Single reflow

    โœ… Best Practices

    • โœ“
      Use querySelector/querySelectorAll โ€” Most flexible and modern approach
    • โœ“
      Prefer classList over style โ€” Keep styling in CSS, logic in JavaScript
    • โœ“
      Use textContent for user input โ€” Prevents XSS attacks
    • โœ“
      Cache element selections โ€” Store references in variables instead of querying repeatedly
    • โœ“
      Use DocumentFragment for bulk operations โ€” Better performance
    • โœ“
      Always check if elements exist โ€” Prevents null reference errors
    • โœ“
      Use semantic HTML โ€” Makes DOM manipulation easier and more accessible

    ๐Ÿงช Interactive Code Practice

    Try out DOM manipulation in this live editor. The code demonstrates selecting, creating, and modifying elements.

    DOM Manipulation Practice

    Practice DOM manipulation techniques

    Try it Yourself ยป
    JavaScript
    // ========================================
    // DOM MANIPULATION PRACTICE
    // ========================================
    
    console.log("๐ŸŒณ DOM Manipulation Demo\n");
    
    // 1. Selecting Elements
    console.log("=== Selecting Elements ===");
    const body = document.body;
    console.log("Body element:", body.tagName);
    
    // 2. Creating a New Element
    console.log("\n=== Creating Elements ===");
    const card = document.createElement("div");
    card.textContent = "Hello from JavaScript! ๐Ÿ‘‹";
    card.style.padding = "20px";
    car
    ...

    ๐Ÿ“š Quick Reference Guide

    ๐Ÿ” Selection Methods

    • getElementById(id) โ€” Get element by ID
    • querySelector(selector) โ€” First match (CSS selector)
    • querySelectorAll(selector) โ€” All matches
    • getElementsByClassName() โ€” By class name
    • getElementsByTagName() โ€” By tag name

    ๐Ÿ—๏ธ Creation Methods

    • createElement(tag) โ€” Create new element
    • appendChild(element) โ€” Add as last child
    • insertBefore(new, ref) โ€” Insert before reference
    • removeChild(element) โ€” Remove child element
    • element.remove() โ€” Remove element itself

    โœ๏ธ Content Methods

    • textContent โ€” Get/set text (safe)
    • innerHTML โ€” Get/set HTML (powerful)
    • value โ€” Get/set form input value
    • innerText โ€” Get/set visible text

    ๐ŸŽจ Style & Class Methods

    • element.style.property โ€” Set inline style
    • classList.add() โ€” Add CSS class
    • classList.remove() โ€” Remove CSS class
    • classList.toggle() โ€” Toggle CSS class
    • classList.contains() โ€” Check if class exists

    ๐Ÿ”ง Attribute Methods

    • getAttribute(name) โ€” Get attribute value
    • setAttribute(name, val) โ€” Set attribute
    • removeAttribute(name) โ€” Remove attribute
    • hasAttribute(name) โ€” Check if exists
    • dataset.property โ€” Access data-* attributes

    ๐Ÿ”„ Traversal Methods

    • parentElement โ€” Get parent element
    • children โ€” Get child elements
    • firstElementChild โ€” First child
    • lastElementChild โ€” Last child
    • nextElementSibling โ€” Next sibling

    ๐ŸŽฏ Practice Challenges

    Test your DOM manipulation skills with these challenges:

    Challenge 1: Profile Card Creator

    Create a function that generates a user profile card with:

    • โ€ข Profile picture (use an img element)
    • โ€ข Name and role
    • โ€ข Background color based on role (admin = blue, user = green)
    • โ€ข Click event that logs the user's details

    Challenge 2: Dynamic Form Validator

    Create a form validator that:

    • โ€ข Selects an input field
    • โ€ข Adds a red border if input is empty
    • โ€ข Shows an error message below the field
    • โ€ข Removes errors when user types

    Challenge 3: Color Palette Generator

    Build a function that:

    • โ€ข Creates 5 colored div boxes
    • โ€ข Each box has a random background color
    • โ€ข Displays the hex code in the box
    • โ€ข Clicking a box copies the color code

    Challenge 4: Table Row Striping

    Write code that:

    • โ€ข Selects all rows in a table
    • โ€ข Adds "odd" or "even" class to alternating rows
    • โ€ข Adds hover effect using classList
    • โ€ข Makes clicking a row highlight it

    ๐Ÿ’ก Bonus Challenge:

    Build a mini shopping cart that lets users add items, increase quantity, remove items, and see the total price update in real-time โ€” all using DOM manipulation!

    ๐Ÿ’ฌ Recap

    • โœ“The DOM is a tree representation of your HTML that JavaScript can manipulate
    • โœ“Use querySelector/querySelectorAll for modern, flexible element selection
    • โœ“textContent is safe for user input, innerHTML is powerful but risky
    • โœ“classList is the best way to manage CSS classes dynamically
    • โœ“You can create, modify, and delete elements on the fly
    • โœ“Always check if elements exist before manipulating them
    • โœ“DOM manipulation is what makes web pages interactive and dynamic

    ๐Ÿ’ก Final Thought

    DOM manipulation is the bridge between your data and what users see. Master it, and you can build anything โ€” from simple counters to complex web applications!

    End of Lesson 4 โ€” DOM Manipulation

    Next up: Learn how to respond to user actions with Event Handling! ๐ŸŽ‰

    ๐Ÿ“‹ Quick Reference โ€” DOM Manipulation

    TaskCode
    Select elementdocument.querySelector('.btn')
    Change textel.textContent = "Hello"
    Add classel.classList.add('active')
    Create elementdocument.createElement('div')
    Remove elementel.remove()

    Lesson 4 Complete โ€” DOM Manipulation!

    You can now select, modify, create, and remove HTML elements using JavaScript โ€” making your webpages truly dynamic!

    Up next: JavaScript Events โ€” respond to clicks, keyboard presses, and more! โšก

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy Policy โ€ข Terms of Service