DOM Manipulation

DOM (Document Object Model) manipulation is a critical skill in web development. It allows you to dynamically change the content, structure, and style of a webpage using JavaScript. Understanding how to interact with the DOM is essential for creating interactive and dynamic web applications.

1. Understanding the DOM

The DOM is a hierarchical representation of the HTML document. It consists of nodes and objects representing elements, attributes, and text in the document. JavaScript can access and manipulate the DOM to update the webpage dynamically.

Example of an HTML structure:

<!DOCTYPE html>
<html>
  <head>
    <title>My Webpage</title>
  </head>
  <body>
    <h1 id="header">Welcome to My Webpage</h1>
    <p class="description">This is a simple paragraph.</p>
    <ul id="itemList">
      <li>Item 1</li>
      <li>Item 2</li>
      <li>Item 3</li>
    </ul>
    <button id="changeButton">Change Content</button>
    <script src="script.js"></script>
  </body>
</html>

2. Selecting Elements

To manipulate the DOM, you first need to select the elements you want to change. You can use various methods to select elements in the DOM.

  • getElementById: Selects an element by its ID.

  • getElementsByClassName: Selects elements by their class name.

  • getElementsByTagName: Selects elements by their tag name.

  • querySelector: Selects the first element that matches a CSS selector.

  • querySelectorAll: Selects all elements that match a CSS selector.

Example:

// Selecting elements
let header = document.getElementById("header");
let paragraphs = document.getElementsByClassName("description");
let listItems = document.getElementsByTagName("li");
let firstItem = document.querySelector("#itemList li");
let allItems = document.querySelectorAll("#itemList li");

console.log(header); // <h1 id="header">Welcome to My Webpage</h1>
console.log(paragraphs); // HTMLCollection of <p class="description"> elements
console.log(listItems); // HTMLCollection of <li> elements
console.log(firstItem); // <li>Item 1</li>
console.log(allItems); // NodeList of <li> elements

3. Changing Content

You can change the content of elements using properties like innerHTML, textContent, and innerText.

  • innerHTML: Sets or returns the HTML content of an element.

  • textContent: Sets or returns the text content of an element.

  • innerText: Similar to textContent, but also respects CSS styling (e.g., display: none).

Example:

// Changing content
header.innerHTML = "Hello, World!";
paragraphs[0].textContent = "This is an updated paragraph.";
firstItem.innerText = "Updated Item 1";

4. Modifying Styles

You can change the styles of elements using the style property.

Example:

// Modifying styles
header.style.color = "blue";
header.style.fontSize = "2em";
header.style.textAlign = "center";

paragraphs[0].style.backgroundColor = "lightgray";

5. Creating and Removing Elements

You can create new elements and add them to the DOM, or remove existing elements.

Example:

// Creating a new element
let newItem = document.createElement("li");
newItem.textContent = "New Item";

// Adding the new element to the list
let itemList = document.getElementById("itemList");
itemList.appendChild(newItem);

// Removing an element
let firstItem = itemList.firstElementChild;
itemList.removeChild(firstItem);

6. Event Listeners

You can attach event listeners to elements to respond to user actions like clicks, key presses, and mouse movements.

Example:

// Adding an event listener
let button = document.getElementById("changeButton");
button.addEventListener("click", function() {
  header.textContent = "Content Changed!";
  itemList.innerHTML += "<li>Another New Item</li>";
});

In this example, clicking the button will change the header text and add a new item to the list.

7. Use Case project - a Todo-List:

Suppose you're building a simple to-do list application. You want to allow users to add new items to the list and remove items.

HTML:

<!DOCTYPE html>
<html>
  <head>
    <title>To-Do List</title>
  </head>
  <body>
    <h1>To-Do List</h1>
    <input type="text" id="newItemInput" placeholder="New item" />
    <button id="addItemButton">Add Item</button>
    <ul id="toDoList">
      <li>Sample Item</li>
    </ul>
    <script src="todo.js"></script>
  </body>
</html>

JavaScript:

// Selecting elements
let newItemInput = document.getElementById("newItemInput");
let addItemButton = document.getElementById("addItemButton");
let toDoList = document.getElementById("toDoList");

// Adding an event listener to the button
addItemButton.addEventListener("click", function() {
  let newItemText = newItemInput.value;
  if (newItemText !== "") {
    let newItem = document.createElement("li");
    newItem.textContent = newItemText;

    // Adding a remove button to each new item
    let removeButton = document.createElement("button");
    removeButton.textContent = "Remove";
    removeButton.addEventListener("click", function() {
      toDoList.removeChild(newItem);
    });
    newItem.appendChild(removeButton);

    toDoList.appendChild(newItem);
    newItemInput.value = ""; // Clear the input
  }
});

In this example:

  • We select the input, button, and list elements.

  • We add an event listener to the button that creates a new list item with the input text when clicked.

  • Each new item includes a "Remove" button that, when clicked, removes the item from the list.

This use case demonstrates how to dynamically manipulate the DOM to create interactive web applications. Understanding DOM manipulation is essential for building responsive and user-friendly web interfaces. As you progress, you'll learn more advanced techniques and best practices for working with the DOM effectively.


Help us improve the content 🤩

You can leave comments here.

Last updated