Event Delegation & Manipulating Classes in JavaScript DOM

Payal PorwalPayal Porwal
2 min read

JavaScript provides powerful techniques for handling events efficiently using event delegation and managing CSS classes dynamically with the classList property.


1. Event Delegation

What It Does:

  • Allows handling multiple child elements' events using a single event listener on a parent element.

  • Uses event.target to identify which child element triggered the event.

  • Improves performance by reducing the number of event listeners in the document.

Syntax:

document.getElementById("parent").addEventListener("click", function(event) {
  if (event.target.matches(".child")) {
    console.log("Child element clicked:", event.target.textContent);
  }
});

Real-Life Examples:

  1. Handling Click Events on a List of Items Dynamically

     <ul id="itemList">
       <li class="item">Item 1</li>
       <li class="item">Item 2</li>
       <li class="item">Item 3</li>
     </ul>
     <script>
       document.getElementById("itemList").addEventListener("click", function(event) {
         if (event.target.classList.contains("item")) {
           alert("Clicked on: " + event.target.textContent);
         }
       });
     </script>
    
  2. Managing a Button Group Dynamically

     <div id="buttonContainer">
       <button class="btn">Button 1</button>
       <button class="btn">Button 2</button>
     </div>
     <script>
       document.getElementById("buttonContainer").addEventListener("click", function(event) {
         if (event.target.classList.contains("btn")) {
           event.target.style.backgroundColor = "green";
         }
       });
     </script>
    
  3. Handling Form Inputs Dynamically

     <div id="formContainer">
       <input type="text" class="input-field" placeholder="Type here">
     </div>
     <script>
       document.getElementById("formContainer").addEventListener("input", function(event) {
         if (event.target.classList.contains("input-field")) {
           console.log("User typed: " + event.target.value);
         }
       });
     </script>
    

2. Manipulating Classes (classList)

What It Does:

  • Allows adding, removing, toggling, and checking for CSS classes dynamically.

  • Useful for styling elements without modifying inline styles directly.

Methods:

  1. classList.add("className") – Adds a class.

  2. classList.remove("className") – Removes a class.

  3. classList.toggle("className") – Toggles a class (adds if absent, removes if present).

  4. classList.contains("className") – Checks if an element has a class.

Syntax:

document.getElementById("element").classList.add("newClass");
document.getElementById("element").classList.remove("oldClass");
document.getElementById("element").classList.toggle("toggleClass");

Real-Life Examples:

  1. Adding a Class When Button Clicked

     <button id="myButton">Click Me</button>
     <script>
       document.getElementById("myButton").addEventListener("click", function() {
         this.classList.add("clicked");
       });
     </script>
     <style>
       .clicked { background-color: red; color: white; }
     </style>
    
  2. Removing a Class on Hover

     <div id="hoverBox" class="highlight">Hover over me</div>
     <script>
       document.getElementById("hoverBox").addEventListener("mouseover", function() {
         this.classList.remove("highlight");
       });
     </script>
     <style>
       .highlight { background-color: yellow; }
     </style>
    
  3. Toggling a Dark Mode Class

     <button id="darkModeBtn">Toggle Dark Mode</button>
     <script>
       document.getElementById("darkModeBtn").addEventListener("click", function() {
         document.body.classList.toggle("dark-mode");
       });
     </script>
     <style>
       .dark-mode { background-color: black; color: white; }
     </style>
    

Conclusion

  • Event delegation improves efficiency by using a single event listener for multiple elements.

  • event.target helps identify the clicked element inside a parent container.

  • classList methods allow dynamic class manipulation, making UI interactions smoother.

Mastering these techniques will help create dynamic, interactive, and efficient web applications! 🚀

10
Subscribe to my newsletter

Read articles from Payal Porwal directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Payal Porwal
Payal Porwal

Hi there, tech enthusiasts! I'm a passionate Software Developer driven by a love for continuous learning and innovation. I thrive on exploring new tools and technologies, pushing boundaries, and finding creative solutions to complex problems. What You'll Find Here On my Hashnode blog, I share: 🚀 In-depth explorations of emerging technologies 💡 Practical tutorials and how-to guides 🔧Insights on software development best practices 🚀Reviews of the latest tools and frameworks 💡 Personal experiences from real-world projects. Join me as we bridge imagination and implementation in the tech world. Whether you're a seasoned pro or just starting out, there's always something new to discover! Let’s connect and grow together! 🌟