Category: DOM Manipulation

The Document Object Model (DOM) allows you to dynamically update web pages in response to user actions or data changes. In this category, you’ll learn how to select elements, modify content and attributes, apply styles, and manage classes using JavaScript. Topics also cover creating, appending, and removing nodes efficiently, as well as optimizing DOM updates for better performance.

  • Creating, Appending, and Removing DOM Nodes

    Creating, Appending, and Removing DOM Nodes

    When working with web pages, the Document Object Model (DOM) allows JavaScript to dynamically manipulate HTML elements — adding new content, updating structures, or removing elements entirely. Understanding how to create, append, and remove DOM nodes is key to building interactive and efficient web experiences.


    1. What Are DOM Nodes?

    Every element, text, or attribute in an HTML document is represented as a node in the DOM tree. For example, a <div> tag, a text string inside it, or even its attributes like id or class are all nodes that can be accessed and modified using JavaScript.


    2. Creating New DOM Elements

    To dynamically add new elements, JavaScript provides the document.createElement() method.

    const newDiv = document.createElement('div');
    newDiv.textContent = 'Hello, this is a new div!';
    

    This creates a <div> element, but it isn’t visible yet because it hasn’t been added to the document.


    3. Appending Nodes to the DOM

    After creating a node, you can attach it to an existing element in the DOM using appendChild() or append().

    const container = document.getElementById('container');
    container.appendChild(newDiv);
    

    Now, the newly created <div> will appear inside the element with the ID container.

    Difference between append() and appendChild():

    • appendChild() only accepts nodes.
    • append() can handle text strings and multiple nodes.

    Example:

    container.append('Some text', newDiv);
    

    4. Inserting Elements Before or After

    Sometimes you need to insert an element at a specific position rather than just appending it to the end.

    • Before a specific element:
    container.insertBefore(newDiv, container.firstChild);
    
    • After a specific element:
      There’s no direct insertAfter(), but you can use insertBefore() with nextSibling.
    container.insertBefore(newDiv, existingElement.nextSibling);
    

    5. Removing DOM Elements

    To delete an element, you can use removeChild() or the modern remove() method.

    Using removeChild():

    container.removeChild(newDiv);
    

    Using remove() (simpler and modern):

    newDiv.remove();
    

    This completely deletes the element from the DOM.


    6. Example: Adding and Removing a List Item

    Here’s a quick example combining all three actions:

    const list = document.getElementById('myList');
    
    // Create a new list item
    const newItem = document.createElement('li');
    newItem.textContent = 'New Item';
    
    // Append it to the list
    list.appendChild(newItem);
    
    // Remove it after 3 seconds
    setTimeout(() => {
      newItem.remove();
    }, 3000);
    

    7. Best Practices

    • Reuse elements when possible instead of recreating them each time.
    • Use document.createDocumentFragment() for bulk insertions — it minimizes reflows and improves performance.
    • Always ensure you’re appending to the correct parent to avoid misplaced elements.

    Conclusion

    Creating, appending, and removing DOM nodes gives you direct control over your web page’s structure. Whether you’re building a dynamic list, updating content in real-time, or manipulating user interface elements, mastering these DOM methods is a foundational skill in front-end development.

  • Changing Content and Attributes Dynamically

    Changing Content and Attributes Dynamically

    When building interactive web pages, one of the most powerful abilities JavaScript offers is the capability to change content and attributes dynamically. This allows developers to update what users see or interact with, without reloading the entire page. Whether you’re working on a static site or integrating scripts into WordPress via Gutenberg blocks, understanding this concept is key to creating engaging user experiences.


    Why Dynamic Changes Matter

    Dynamic updates improve usability and make your site feel more responsive. Imagine updating a product price when a user selects a different variant, changing an image when hovering over a thumbnail, or modifying a button’s text after a form submission—all of this is done through dynamic content manipulation.


    Accessing and Updating HTML Content

    To modify the text or HTML content of an element, JavaScript provides several handy properties and methods.

    Example: Changing Text Content

    const heading = document.getElementById('title');
    heading.textContent = 'Welcome to My Updated Page!';
    

    Here, .textContent replaces the existing text with a new one.

    Example: Updating Inner HTML

    const container = document.querySelector('.content');
    container.innerHTML = '<p>This is <strong>dynamically</strong> added content!</p>';
    

    .innerHTML allows you to inject HTML markup directly into an element.

    ⚠️ Tip: Use .textContent when inserting plain text and .innerHTML when you need to add HTML elements.


    Modifying Element Attributes

    JavaScript also makes it easy to update element attributes such as src, href, or alt.

    Example: Changing an Image Source

    const image = document.querySelector('img');
    image.setAttribute('src', 'new-image.jpg');
    image.setAttribute('alt', 'Updated description');
    

    Alternatively, you can update attributes directly:

    image.src = 'new-image.jpg';
    image.alt = 'Updated description';
    

    Toggling Classes and Styles

    Dynamic style changes can make your site more interactive and visually appealing.

    Example: Toggling Classes

    const box = document.querySelector('.box');
    box.classList.toggle('highlight');
    

    .classList.toggle() adds a class if it’s missing and removes it if it’s already present.

    Example: Inline Style Updates

    box.style.backgroundColor = 'lightblue';
    box.style.padding = '10px';
    

    Combining Content and Attribute Updates

    You can also combine updates for a more complex effect. For instance, changing a button label and disabling it after it’s clicked:

    const button = document.querySelector('#submit-btn');
    button.textContent = 'Submitting...';
    button.disabled = true;
    

    Using in WordPress with Gutenberg

    In a WordPress Gutenberg block, you can include these scripts within your block’s JavaScript file or enqueue them using wp_enqueue_script() in your theme or plugin.

    For example:

    function enqueue_dynamic_scripts() {
        wp_enqueue_script(
            'dynamic-content',
            get_template_directory_uri() . '/js/dynamic-content.js',
            array(),
            null,
            true
        );
    }
    add_action('wp_enqueue_scripts', 'enqueue_dynamic_scripts');
    

    Then, you can safely manipulate your block’s DOM once it’s rendered.


    Final Thoughts

    Changing content and attributes dynamically is a cornerstone of modern front-end development. Whether you’re enhancing a simple webpage or adding interactivity to your WordPress site, mastering these JavaScript techniques helps you create seamless, real-time experiences for your users.

    Experiment with different elements and interactions to see how small changes can make a big impact on your site’s usability and appeal.

  • Selecting DOM Elements in JavaScript: A Complete Guide

    Selecting DOM Elements in JavaScript: A Complete Guide

    When working with JavaScript, one of the most common tasks you’ll perform is selecting and manipulating elements in the DOM (Document Object Model). Whether you want to change text, apply styles, or add interactivity, understanding how to select elements is fundamental. In this guide, we’ll walk through the most commonly used methods to select DOM elements efficiently.


    1. What Is the DOM?

    The Document Object Model (DOM) represents the structure of a web page as a tree of nodes. Each element, attribute, and text on a webpage is a node in this tree. JavaScript interacts with these nodes to read, update, or modify them dynamically.


    2. Selecting Elements by ID

    The easiest and fastest way to select an element is by its ID using the getElementById() method.

    const heading = document.getElementById('main-title');
    heading.style.color = 'blue';
    
    • IDs should be unique within a page.
    • Returns a single element object.

    3. Selecting Elements by Class Name

    If you want to select multiple elements that share the same class, use getElementsByClassName().

    const items = document.getElementsByClassName('menu-item');
    for (let item of items) {
      item.style.fontWeight = 'bold';
    }
    
    • Returns an HTMLCollection, which is a live list of elements.
    • You can loop through the collection using a for...of loop or convert it to an array.

    4. Selecting Elements by Tag Name

    Use getElementsByTagName() to target elements by their HTML tag.

    const paragraphs = document.getElementsByTagName('p');
    console.log(paragraphs.length); // Number of paragraph elements
    
    • Returns all matching tags as an HTMLCollection.
    • Ideal for selecting elements like <p>, <div>, or <img>.

    5. Using querySelector() and querySelectorAll()

    Modern JavaScript introduced powerful methods: querySelector() and querySelectorAll(). These let you select elements using CSS selectors.

    const firstItem = document.querySelector('.menu-item');
    const allItems = document.querySelectorAll('.menu-item');
    
    • querySelector() returns the first matching element.
    • querySelectorAll() returns a NodeList (not live).
    • You can use any CSS selector like #id, .class, or div > p.

    Example with complex selectors:

    const activeLink = document.querySelector('nav ul li.active a');
    

    6. Combining Selection Methods

    You can chain or combine these methods to narrow down your selections.

    const section = document.getElementById('about');
    const headings = section.getElementsByTagName('h2');
    

    This targets all <h2> elements inside the #about section.


    7. Selecting Form Elements

    To access form elements easily:

    const form = document.forms['contactForm'];
    const input = form['email'];
    
    • document.forms returns all forms in the document.
    • You can access form inputs by name.

    8. Best Practices for Selecting Elements

    • Prefer querySelector and querySelectorAll for flexibility.
    • Keep IDs unique for faster lookups.
    • Cache frequently accessed elements in variables.
    • Use descriptive class names to simplify selection.

    9. Wrapping Up

    Selecting DOM elements is the foundation of dynamic and interactive web development. Whether you’re adding animations, handling user input, or modifying layouts, these methods give you precise control over your webpage content.

    Once you master element selection, you can move on to manipulating the DOM, handling events, and creating dynamic content—the next steps in becoming a skilled front-end developer.


    Ready to take the next step?
    Explore our next guide on “Creating, Appending, and Removing DOM Nodes in JavaScript” to continue building your DOM manipulation skills.