JavaScript DOM Manipulation | Extraparse

JavaScript DOM Manipulation

October 06, 202310 min read1836 words

Interact with the Document Object Model to dynamically update web pages. Comprehensive guide with examples and best practices for mastering DOM Manipulation in JavaScript.

Table of Contents

Author: Extraparse

DOM Manipulation

The Document Object Model (DOM) is a vital programming interface for web documents, enabling JavaScript to interact with and manipulate the structure, style, and content of a webpage dynamically. By representing the page so that programs can change the document structure, style, and content, the DOM allows developers to create interactive and responsive web applications. Mastering DOM manipulation is essential for enhancing user experiences and building dynamic web interfaces.

DOM Structure Diagram

What You'll Learn

  • Understanding the DOM: Learn the basics of the DOM structure and its relationship with HTML.
  • Selecting DOM Elements: Use various methods to select and target elements within the DOM.
  • Modifying Content and Attributes: Change the content and attributes of DOM elements programmatically.
  • Styling Elements: Dynamically apply and modify CSS styles through JavaScript.
  • Creating and Removing Elements: Add new elements to the DOM and remove existing ones.
  • Event Handling: Respond to user interactions by attaching event listeners to DOM elements.
  • Traversing the DOM: Navigate between parent, child, and sibling elements within the DOM tree.
  • Best Practices: Employ best practices for efficient and maintainable DOM manipulation.
  • Interactive Exercises: Practice selecting and manipulating DOM elements through hands-on exercises.

Understanding the DOM

The DOM represents the structure of an HTML document as a hierarchical tree of nodes. Each node corresponds to an element, attribute, or text within the document. This tree structure allows JavaScript to interact with and modify the webpage dynamically. Understanding the DOM is crucial because it serves as the bridge between HTML and JavaScript, enabling the creation of interactive and dynamic web pages.

Detailed DOM Structure

The DOM tree starts with the document node, which is the root of the tree. Underneath it, you'll find nodes such as <html>, <head>, <body>, and all other HTML elements. Each element node can have child nodes, creating a nested structure that mirrors the HTML document.

For example, consider the following HTML snippet:

1<!DOCTYPE html>
2<html>
3 <head>
4 <title>Sample Page</title>
5 </head>
6 <body>
7 <div id="container">
8 <h1 class="title">Welcome</h1>
9 <p>This is a sample paragraph.</p>
10 </div>
11 </body>
12</html>

The corresponding DOM tree would have document as the root, with <html> as its child, followed by <head> and <body>, and so on, forming a structured hierarchy.

Selecting DOM Elements

Selecting the right elements is the first step in DOM manipulation. JavaScript provides several methods to select and target elements within the DOM.

Methods to Select Elements

  1. getElementById

    Selects a single element by its unique ID.

    1const container = document.getElementById("container");
  2. getElementsByClassName

    Selects all elements with the specified class name. Returns an HTMLCollection.

    1const titles = document.getElementsByClassName("title");
  3. getElementsByTagName

    Selects all elements with the specified tag name. Returns an HTMLCollection.

    1const paragraphs = document.getElementsByTagName("p");
  4. querySelector

    Selects the first element that matches a CSS selector.

    1const firstTitle = document.querySelector(".title");
  5. querySelectorAll

    Selects all elements that match a CSS selector. Returns a NodeList.

    1const allTitles = document.querySelectorAll(".title");

Practical Examples

1// Selecting by ID
2const header = document.getElementById("header");
3
4// Selecting by class name
5const buttons = document.getElementsByClassName("btn");
6
7// Selecting by tag name
8const listItems = document.getElementsByTagName("li");
9
10// Using querySelector for complex selectors
11const activeButton = document.querySelector("button.active");
12
13// Using querySelectorAll for multiple elements
14const allButtons = document.querySelectorAll("button");

Modifying Content and Attributes

Changing the content and attributes of DOM elements allows for dynamic updates to the webpage.

Changing Text Content

Use the textContent property to modify the text within an element.

1const heading = document.getElementById("main-heading");
2heading.textContent = "Updated Heading Text";

Changing HTML Content

Use the innerHTML property to modify the HTML inside an element.

1const container = document.getElementById("container");
2container.innerHTML = "<p>New paragraph added dynamically.</p>";

Changing Element Attributes

Use the setAttribute method to change attributes like src, href, or class.

1const image = document.getElementById("logo");
2image.setAttribute("src", "new-logo.png");
3
4const link = document.querySelector("a");
5link.setAttribute("href", "https://www.newsite.com");

Practical Examples

1// Changing the source of an image
2document.getElementById("profile-pic").src = "profile-new.jpg";
3
4// Updating the href of a link
5document.querySelector(".nav-link").href = "https://www.example.com";
6
7// Modifying the class of an element
8const alertBox = document.getElementById("alert");
9alertBox.className = "alert alert-success";

Styling Elements

Dynamically applying and modifying CSS styles enhances the visual aspects of web pages.

Applying Inline Styles

Modify the style property to change individual CSS properties.

1const box = document.getElementById("box");
2box.style.backgroundColor = "blue";
3box.style.width = "200px";
4box.style.height = "200px";

Adding and Removing CSS Classes

Use classList to add, remove, or toggle classes for better style management.

1const button = document.querySelector("button");
2
3// Adding a class
4button.classList.add("active");
5
6// Removing a class
7button.classList.remove("inactive");
8
9// Toggling a class
10button.classList.toggle("hidden");

Practical Examples

1// Changing multiple styles at once
2const header = document.getElementById("header");
3header.style.color = "white";
4header.style.backgroundColor = "black";
5header.style.padding = "10px";
6
7// Toggling visibility
8const menu = document.getElementById("menu");
9menu.classList.toggle("visible");
10
11// Adding multiple classes
12const card = document.querySelector(".card");
13card.classList.add("shadow", "rounded");

Creating and Removing Elements

Manipulating the DOM often involves adding new elements or removing existing ones to update the content dynamically.

Creating New Elements

Use createElement to create a new element and appendChild or insertBefore to add it to the DOM.

1const newDiv = document.createElement("div");
2newDiv.className = "new-div";
3newDiv.textContent = "This is a new div element.";
4
5const container = document.getElementById("container");
6container.appendChild(newDiv);

Removing Elements

Use removeChild or the remove method to delete elements from the DOM.

1const oldDiv = document.getElementById("old-div");
2oldDiv.parentNode.removeChild(oldDiv);
3
4// Or using remove
5oldDiv.remove();

Practical Examples

1// Creating and inserting a new list item
2const ul = document.querySelector("ul");
3const li = document.createElement("li");
4li.textContent = "New List Item";
5ul.appendChild(li);
6
7// Removing the first child of a list
8const firstItem = ul.firstChild;
9ul.removeChild(firstItem);

Event Handling

Responding to user interactions is a cornerstone of interactive web applications. JavaScript allows you to attach event listeners to DOM elements to handle various events.

Types of Events

  • Click Events: Triggered when an element is clicked.
  • Mouse Events: Include mouseover, mouseout, mousemove, etc.
  • Keyboard Events: Include keydown, keyup, keypress, etc.
  • Form Events: Include submit, change, focus, blur, etc.
  • Touch Events: For handling touch interactions on mobile devices.

Attaching Event Listeners

Use the addEventListener method to attach events to elements.

1const button = document.getElementById("submit-button");
2
3// Click event
4button.addEventListener("click", function () {
5 alert("Button clicked!");
6});
7
8// Mouseover event
9button.addEventListener("mouseover", function () {
10 button.style.backgroundColor = "green";
11});
12
13// Keyboard event
14document.addEventListener("keydown", function (event) {
15 console.log(`Key pressed: ${event.key}`);
16});

Practical Examples

1// Handling form submission
2const form = document.querySelector("form");
3form.addEventListener("submit", function (event) {
4 event.preventDefault();
5 // Process form data
6});
7
8// Toggling a menu on click
9const menuButton = document.getElementById("menu-button");
10const menu = document.getElementById("menu");
11
12menuButton.addEventListener("click", function () {
13 menu.classList.toggle("open");
14});
15
16// Changing input placeholder on focus
17const input = document.getElementById("search-input");
18input.addEventListener("focus", function () {
19 input.placeholder = "Start typing...";
20});

Traversing the DOM

Navigating through the DOM tree allows you to move between related elements efficiently.

  • parentNode: Accesses the parent of the current node.
  • childNodes: Returns a live NodeList of child nodes.
  • firstChild / lastChild: Accesses the first or last child node.
  • nextSibling / previousSibling: Accesses the next or previous sibling node.
  • children: Returns a live HTMLCollection of child elements (excluding text and comment nodes).

Practical Examples

1const listItem = document.querySelector("li.current");
2
3// Accessing the parent element
4const parent = listItem.parentNode;
5
6// Accessing child elements
7const children = parent.children;
8
9// Moving to the next sibling
10const nextItem = listItem.nextSibling;
11
12// Accessing the first child
13const firstChild = parent.firstChild;

Best Practices

Efficient and maintainable DOM manipulation is crucial for building robust web applications. Here are some best practices to follow:

  1. Minimize Direct DOM Manipulation:

    • Reduce the number of times the DOM is updated. Batch changes together to improve performance.
  2. Use Event Delegation:

    • Instead of attaching event listeners to multiple child elements, attach a single listener to a parent element.
    1const list = document.getElementById("item-list");
    2list.addEventListener("click", function (event) {
    3 if (event.target && event.target.matches("li.item")) {
    4 console.log("List item clicked:", event.target.textContent);
    5 }
    6});
  3. Cache DOM References:

    • Store references to frequently accessed elements to avoid repeated queries.
    1const nav = document.getElementById("navbar");
    2// Use 'nav' variable instead of querying again
  4. Avoid Inline Styles:

    • Prefer adding or removing CSS classes over manipulating styles directly for better separation of concerns.
  5. Use Frameworks and Libraries When Appropriate:

    • Leverage tools like React, Vue, or jQuery to simplify complex DOM manipulations.
  6. Clean Up Event Listeners:

    • Remove event listeners when they are no longer needed to prevent memory leaks.
    1function handleClick() {
    2 // Event handling logic
    3}
    4
    5element.addEventListener("click", handleClick);
    6
    7// To remove
    8element.removeEventListener("click", handleClick);
  7. Optimize for Performance:

    • Utilize techniques like debouncing and throttling for events that fire frequently, such as scroll or resize events.
  8. Use Semantic HTML:

    • Write clean, semantic HTML to make DOM manipulation more intuitive and accessible.

Visual Diagrams

Understanding the relationship between HTML elements and their corresponding DOM nodes can be enhanced with visual aids. Below is a diagram illustrating a simple DOM tree structure:

DOM Tree Diagram

Interactive Exercises

Practice makes perfect. Try the exercises below to reinforce your understanding of DOM manipulation.

Exercise 1: Selecting Elements

  1. Select the element with the ID main-header and change its text to "Welcome to the DOM Tutorial".
  2. Select all elements with the class highlight and change their background color to yellow.
1// Your code here

Exercise 2: Creating and Removing Elements

  1. Create a new <li> element with the text "New Item" and append it to the <ul> with the ID item-list.
  2. Remove the last <li> element from the same list.
1// Your code here

Exercise 3: Event Handling

  1. Attach a click event listener to the button with the ID toggle-button that toggles the visibility of the element with the ID toggle-content.
  2. Attach a mouseover event to all elements with the class card that changes their border color to blue on hover.
1// Your code here

Exercise 4: Styling Elements

  1. Select the <header> element and add a new CSS class sticky that makes the header fixed at the top of the page.
  2. Change the font size of all <p> elements to 18px using JavaScript.
1// Your code here

Exercise 5: Traversing the DOM

  1. Starting from an element with the class active, navigate to its parent and change its background color to green.
  2. Find the next sibling of an element with the ID section-2 and hide it.
1// Your code here

Conclusion

Mastering DOM manipulation is a fundamental skill for any JavaScript developer. By understanding the structure of the DOM, effectively selecting and modifying elements, handling events, and following best practices, you can create dynamic and interactive web applications that provide seamless user experiences. Continue practicing with the exercises provided and explore more advanced topics to further enhance your skills.

xtelegramfacebooktiktoklinkedin
Author: Extraparse

Comments

You must be logged in to comment.

Loading comments...