Mastering JavaScript DOM: Core Concepts and Practical Element Manipulation

JavaScript Web APIs are built on top of foundational JS syntax, providing pre-built functions for interacting with browser capabilities (BOM) and page elements (DOM). APIs act as pre-built tools for developers, simplifying complex functionality implementation without requiring knowledge of internal source code or mechanisms. Web APIs follow standard input/output patterns with methods and properties, and can be learned using the same approach as built-in JS object methods.

The Document Object Model (DOM) is a W3C-standard interface for manipulating XML or HTML documents, allowing changes to content, structure, and styling. It represents the entire page as a tree of nodes: each document is a single root node, tags become element nodes, and all other content (text, attributes, comments) are node types too.

Element Selection Methods

By ID

document.getElementById() returns a single DOM element matching the specified case-sensitive ID string. The method is called after the DOM loads to ensure the element exists.

<div id="current-date">2024-05-20</div>
<script>
    // Wait for DOM to load by placing script below target element
    const dateElement = document.getElementById('current-date');
    console.log(dateElement); // Logs <div> element
    console.dir(dateElement); // Detailed element properties/methods
</script>

By Tag Name

document.getElementsByTagName() returns a live HTMLCollection of elements matching the tag name. To access individual items, use indexing or iteration.

<ul>
    <li>Top Hits</li>
    <li>New Releases</li>
    <li>Classics</li>
</ul>
<ol id="chart-list">
    <li>1. Blinding Lights</li>
    <li>2. Shape of You</li>
</ol>
<script>
    const listItems = document.getElementsByTagName('li');
    console.log(listItems); // HTMLCollection of all <li> tags
    // Iterate over collection
    for (let idx = 0; idx < listItems.length; idx++) {
        console.log(listItems[idx].textContent);
    }
    // Select from parent element
    const chart = document.getElementById('chart-list');
    const chartEntries = chart.getElementsByTagName('li');
    console.log(chartEntries); // Only <li> tags inside #chart-list
</script>

HTML5 Methods

  • document.getElementsByClassName(): Returns a live HTMLCollection of elements with matching class names.
  • document.querySelector(): Returns the first element matching any valid CSS selector (requires selector prefix: . for class, # for ID).
  • document.querySelectorAll(): Returns a static NodeList of all elements matching a CSS selector.
<div class="card">Music Card 1</div>
<div class="card">Music Card 2</div>
<nav id="main-nav">
    <ul>
        <li>Home</li>
        <li>Playlist</li>
    </ul>
</nav>
<script>
    // Get all cards
    const cards = document.getElementsByClassName('card');
    console.log(cards);
    // Get first card and nav
    const firstCard = document.querySelector('.card');
    const mainNav = document.querySelector('#main-nav');
    console.log(firstCard, mainNav);
    // Get all list items in nav
    const navLinks = document.querySelectorAll('#main-nav li');
    console.log(navLinks);
</script>

Special Elemenst

  • document.body: Direct access to the <body> element
  • document.documentElement: Direct access to the <html> root element

Event Handling Basics

Events are browser-detectable user or system actions that trigger JavaScript code (trigger-response mechanism). Common events include clicks, mouse movement, and focus/blur.

Event Trinity

  1. Event Target: The DOM element that triggered the event
  2. Event Type: The specific action (e.g., click, mouseover)
  3. Event Listener/Handler: The function executed when the event fires

Mouse Events Reference

Event Type Trigger Condition
onclick Left mouse button click
onmouseover Mouse pointer enters target
onmouseout Mouse pointer leaves target
onfocus Element gains keyboadr focus
onblur Element loses keyboard focus
onmousemove Mouse pointer moves over target
onmouseup Mouse button released
onmousedown Mouse button pressed

Event Execution Example

<div id="click-target">Click Me!</div>
<script>
    // 1. Get event target
    const targetDiv = document.getElementById('click-target');
    // 2. Attach event listener
    targetDiv.onclick = function() {
        console.log('I was clicked!');
    };
</script>

Dynamic Content with Events

<style>
    .info-box, .time-display {
        width: 320px;
        height: 32px;
        line-height: 32px;
        color: white;
        background-color: #ff69b4;
        margin: 8px 0;
    }
</style>
<button id="show-time-btn">Show Current Time</button>
<div class="time-display">Waiting for click...</div>
<p class="info-box">Time info will update here</p>
<script>
    function getFormattedDate() {
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        const dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
        const weekday = dayNames[now.getDay()];
        return `Today is: ${year}-${month}-${day} ${weekday}`;
    }

    const timeBtn = document.getElementById('show-time-btn');
    const timeDiv = document.querySelector('.time-display');
    const infoP = document.querySelector('.info-box');

    timeBtn.onclick = function() {
        timeDiv.textContent = getFormattedDate();
    };
    // Initial load update
    infoP.textContent = getFormattedDate();
</script>

Element Manipulation

DOM manipulation allows modifying content, attributes, and styles dynamically.

Content Modification

  • element.innerText: Returns/strips HTML tags, ignores whitespace/newlines
  • element.innerHTML: Returns/strips preserves HTML tags, preserves whitespace/newlines
<div id="content-demo"></div>
<p id="multi-line">
    Sample text
    <span class="highlight">with HTML</span>
</p>
<script>
    const contentDiv = document.getElementById('content-demo');
    contentDiv.innerHTML = '<strong>Dynamic HTML</strong> insertion works!';
    
    const multiLineP = document.getElementById('multi-line');
    console.log(multiLineP.innerText); // Strips tags/newlines
    console.log(multiLineP.innerHTML); // Preserves all
</script>

Attribute Modification

Commonly modified attributes include src, href, id, alt, title, and type (for form elements).

<button id="adele-btn">Adele</button>
<button id="ed-btn">Ed Sheeran</button><br>
<img src="assets/adele.jpg" alt="Adele" id="artist-img">
<script>
    const adeleBtn = document.getElementById('adele-btn');
    const edBtn = document.getElementById('ed-btn');
    const artistImg = document.getElementById('artist-img');

    edBtn.onclick = function() {
        artistImg.src = 'assets/edsheeran.jpg';
        artistImg.alt = 'Ed Sheeran';
        artistImg.title = 'Ed Sheeran - Singer-Songwriter';
    };
    adeleBtn.onclick = function() {
        artistImg.src = 'assets/adele.jpg';
        artistImg.alt = 'Adele';
        artistImg.title = 'Adele - Grammy Winner';
    };
</script>

Form Element Modification

Form elements support manipulation of value, type, checked, selected, and disabled attributes.

<button id="submit-btn">Submit Form</button>
<input type="text" id="username-input" value="Enter username">
<script>
    const submitBtn = document.getElementById('submit-btn');
    const usernameInput = document.getElementById('username-input');

    submitBtn.onclick = function() {
        usernameInput.value = 'Submitted!';
        this.disabled = true;
    };
    // Focus/blur to clear placeholder
    usernameInput.onfocus = function() {
        if (this.value === 'Enter username') {
            this.value = '';
        }
        this.style.color = '#333';
    };
    usernameInput.onblur = function() {
        if (this.value === '') {
            this.value = 'Enter username';
        }
        this.style.color = '#999';
    };
</script>

Style Manipulation

  • Inline Styles (element.style): Directly modifies style attribute (uses camelCase, e.g., fontSize instead of font-size)
  • Class Styles (element.className): Replaces/extends element classList (more efficient for multiple style changes)
<style>
    .product-card {
        width: 120px;
        height: 120px;
        background-color: #ffb3d9;
        margin: 16px;
        float: left;
    }
    .highlighted {
        background-color: #9933ff;
        color: white;
        font-size: 24px;
        margin-top: 40px;
    }
</style>
<div class="product-card">Sample Card</div>
<script>
    const productCard = document.querySelector('.product-card');
    productCard.onclick = function() {
        // Toggle highlighted class (preserve original class)
        this.className = this.className === 'product-card' ? 'product-card highlighted' : 'product-card';
    };
</script>

Toggle Password Visibility

<style>
    .password-container {
        position: relative;
        width: 380px;
        border-bottom: 1px solid #ddd;
        margin: 60px auto;
    }
    .password-container input {
        width: 350px;
        height: 36px;
        border: none;
        outline: none;
    }
    .password-container img {
        position: absolute;
        top: 4px;
        right: 4px;
        width: 28px;
        cursor: pointer;
    }
</style>
<div class="password-container">
    <label for="password">
        <img src="assets/eye-closed.svg" alt="Hide password" id="eye-icon">
    </label>
    <input type="password" id="password" placeholder="Enter password">
</div>
<script>
    const eyeIcon = document.getElementById('eye-icon');
    const passwordInput = document.getElementById('password');
    let isVisible = false;

    eyeIcon.onclick = function() {
        isVisible = !isVisible;
        passwordInput.type = isVisible ? 'text' : 'password';
        eyeIcon.src = isVisible ? 'assets/eye-open.svg' : 'assets/eye-closed.svg';
        eyeIcon.alt = isVisible ? 'Show password' : 'Hide password';
    };
</script>

Password Validation

<style>
    .registration-form {
        width: 600px;
        margin: 80px auto;
    }
    .validation-message {
        display: inline-block;
        font-size: 14px;
        color: #666;
        background: url('assets/info.svg') no-repeat left center;
        padding-left: 24px;
    }
    .invalid {
        color: #dc3545;
        background-image: url('assets/error.svg');
    }
    .valid {
        color: #28a745;
        background-image: url('assets/success.svg');
    }
</style>
<div class="registration-form">
    <input type="password" class="password-input" placeholder="Enter 6-16 character password">
    <p class="validation-message">Password must be 6-16 characters long</p>
</div>
<script>
    const passwordInput = document.querySelector('.password-input');
    const validationMessage = document.querySelector('.validation-message');

    passwordInput.onblur = function() {
        const length = this.value.length;
        if (length < 6 || length > 16) {
            validationMessage.className = 'validation-message invalid';
            validationMessage.textContent = 'Password length must be between 6 and 16 characters';
        } else {
            validationMessage.className = 'validation-message valid';
            validationMessage.textContent = 'Password format is valid';
        }
    };
</script>

Toggle Background (Light/Dark Mode)

<button id="theme-toggle">Toggle Dark Mode</button>
<script>
    const themeToggle = document.getElementById('theme-toggle');
    let isDark = false;

    themeToggle.onclick = function() {
        isDark = !isDark;
        document.body.style.backgroundColor = isDark ? '#1a1a1a' : '#f8f9fa';
        document.body.style.color = isDark ? '#fff' : '#000';
    };
</script>

Tags: javascript DOM Web APIs Event Handling Element Manipulation

Posted on Thu, 07 May 2026 21:48:03 +0000 by staples27