Obafemi Emmanuel

Mastering JavaScript DOM Manipulation

Published 3 months ago

The Document Object Model (DOM) is a programming interface that allows developers to interact with and modify HTML and CSS using JavaScript. Whether you want to change the text of an element, update styles dynamically, or handle user interactions, understanding the DOM is essential for building interactive web applications.

In this blog, we will explore the key aspects of JavaScript DOM manipulation, including selecting elements, modifying HTML & CSS, handling events, event delegation, and dynamically creating and removing elements.


1. Selecting Elements

Before manipulating elements, we need to select them. JavaScript provides several methods to select elements from the DOM.


getElementById()

This method selects an element based on its id attribute.

let title = document.getElementById("main-title");
console.log(title.textContent); // Outputs the text content of the element

getElementsByClassName()

This method selects elements that have a specific class name and returns an HTMLCollection.

let items = document.getElementsByClassName("list-item");
console.log(items[0].textContent); // Outputs the first item's text

getElementsByTagName()

This method selects all elements of a specific tag name (e.g., <p>, <div>, etc.).

let paragraphs = document.getElementsByTagName("p");
console.log(paragraphs.length); // Outputs the number of paragraphs

querySelector() & querySelectorAll()

  • querySelector() selects the first matching element.
  • querySelectorAll() selects all matching elements and returns a NodeList.
let firstItem = document.querySelector(".list-item");
console.log(firstItem.textContent);

let allItems = document.querySelectorAll(".list-item");
console.log(allItems.length);

2. Changing HTML & CSS with JavaScript

After selecting elements, we can modify their properties, styles, and content dynamically.


Changing Text Content

let heading = document.getElementById("main-title");
heading.textContent = "Updated Title";

Changing Inner HTML

let container = document.getElementById("container");
container.innerHTML = "<h2>New Content</h2>";

Modifying CSS Styles

let box = document.querySelector(".box");
box.style.backgroundColor = "blue";
box.style.color = "white";
box.style.padding = "10px";

3. Event Listeners & Handling Events

JavaScript allows you to handle user interactions with event listeners.


Adding an Event Listener

let button = document.getElementById("myButton");
button.addEventListener("click", function() {
    alert("Button Clicked!");
});

Handling Different Events

document.getElementById("inputField").addEventListener("keydown", function(event) {
    console.log("Key pressed: ", event.key);
});

Removing an Event Listener

function showAlert() {
    alert("Clicked!");
}
button.addEventListener("click", showAlert);

// Removing the event listener
document.getElementById("removeBtn").addEventListener("click", function() {
    button.removeEventListener("click", showAlert);
});

4. Event Delegation

Event delegation is a technique where a parent element listens for events on its child elements, improving efficiency for dynamic elements.


Example: Handling Clicks on a List

document.getElementById("list").addEventListener("click", function(event) {
    if (event.target.tagName === "LI") {
        alert("You clicked: " + event.target.textContent);
    }
});

This is useful when adding new elements dynamically since the parent remains in charge of event handling.


5. Creating and Removing Elements Dynamically

JavaScript enables the creation and deletion of HTML elements dynamically.


Creating an Element

let newDiv = document.createElement("div");
newDiv.textContent = "This is a new div!";
document.body.appendChild(newDiv);

Appending an Element to Another Element

let list = document.getElementById("list");
let newItem = document.createElement("li");
newItem.textContent = "New List Item";
list.appendChild(newItem);

Removing an Element

let itemToRemove = document.getElementById("remove-me");
itemToRemove.parentNode.removeChild(itemToRemove);

Alternative: Using remove()

let item = document.getElementById("remove-me");
item.remove();

Conclusion

Mastering JavaScript DOM manipulation is essential for creating dynamic and interactive web applications. By learning how to:

  • Select elements efficiently,
  • Modify HTML and CSS,
  • Handle events,
  • Implement event delegation,
  • Create and remove elements dynamically, you will be able to build powerful user interfaces that enhance the user experience.



Leave a Comment


Choose Colour