listening for events on nested classes

I am looking to dynamically toggle the class "collapsed" on each element with the class "category" when it is clicked. The issue arises when these "category" elements are nested within each other, causing the child elements to also trigger the class change on their parent elements.

For instance

Here's an example of the HTML structure:

<div class="category">
    <div class="category">
        <div class="category"></div>
    </div>
</div>
<div class="category">
    <div class="category"></div>
</div>

This snippet of JavaScript accomplishes the task:

var categories = document.getElementsByClassName("category");
for (var i = 0; i < categories.length; i++) {
    categories[i].addEventListener("click", function () {
        this.classList.toggle("collapsed");
    });
}

However, a problem occurs when clicking on a nested element because the "this" selector will affect not only the current element but also its parent elements with the "category" class.

Answer №1

The reason for this behavior is that the event bubbles up and triggers on all container elements with the specified class. To stop this from happening, you can use the method event.stopPropagation().

var categories = document.getElementsByClassName("category");
for (var i = 0; i < categories.length; i++) {
    categories[i].addEventListener("click", function (e) {
        e.stopPropagation();
        this.classList.toggle("collapsed");
    });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering the error code 'ERR_EMPTY_RESPONSE' while utilizing an AJAX-powered live search feature

My website features a live AJAX search bar that retrieves records from a MySQL database. However, when users repeatedly conduct searches by modifying the search criteria, some web browsers display an error message stating 'ERR_EMPTY_RESPONSE'. ...

Error: Unable to access the 'login' property of an undefined object

An error occurred: Uncaught TypeError: Cannot read property 'login' of undefined........... import Login from '../components/Login.jsx'; import { useDeps, composeWithTracker, composeAll } from 'mantra-core'; export const com ...

Using CSS to Create Text Wrapping

I have a massive string of randomly generated numbers that I am trying to display in a div block. Since the string is quite long, it's currently being shown in one single line. For instance: String str="13,7,5,1,10,7,18,11,17,10,9,16,17,9,6,19,6,13, ...

Error encountered in jQuery validation: Uncaught TypeError - $(...) ""valid is not a function" is displayed with proper references and order

When I try to call a function, I keep getting an error message that says "Uncaught TypeError: $(...).valid is not a function"... JS $('input[data-val=true]').on('blur', function() { $(this).valid(); }); HTML <div class="col-x ...

Strange behavior observed when transclusion is used without cloning

During my experimentation with transclusion, I wanted to test whether the transcluded directive could successfully locate its required parent directive controller after being transcluded under it. The directives used in this experiment are as follows: - Th ...

When hosted, OpenCart encounters a JavaScript error stating that the property "document" cannot be read because it is null

After successfully running opencart on my local machine, I encountered some errors upon uploading it to the hosting/server. The specific error message is as follows: Uncaught TypeError: Cannot read property 'document' of null f.each.contents @ j ...

Issue with 'backface-visibility' CSS3 property not functioning on any versions of Internet Explorer

I'm looking to implement a specific animation in Internet Explorer. The goal is to rotate an image like a coin, displaying a different image on the other side. I suspect that the issue lies with Backface-visibility in IE, but I'm not entirely sur ...

Using JSON data to render images onto a canvas

I am encountering an issue with a JSON array that I'm receiving from PHP. The array is indexed and has the following format (larger in real scenario) [ [ [17, 28, 1, "z"], [28, 31, 6, "b"], [8, 29, 6, "b"] ...

What steps can I take to resolve the spawn unknown error when using npx create-next-app in Visual Studio Code (VSCode)?

Every time I attempt to create a new app using either vscode or cmd, I encounter a spawn unknown error. The error message says "Aborting installation. Unexpected error. Please report it as a bug: Error: spawn UNKNOWN". Unfortunately, the installation abo ...

Assign a value to the input field based on changes made in another input field

I am brand new to the world of JavaScript and currently grappling with setting a value in an input field based on the onchange event of another input field. Here is my code sample for input field 1: <input type='text' onchange='methodTh ...

Jquery code failing to trigger any response

Recently, I quickly created a jQuery script to dynamically populate a paragraph element in order to easily switch between player and server interaction options. However, I am currently facing an issue where my script does not populate as expected. I have a ...

Wrapping dynamic page titles with comment tags in NextJS for cleaner code

I am currently working on NextJS version 12. In my project, I have a file named Layout.js which contains the following code: import Head from "next/head"; const Layout = ({children, pageTitle, mainClass}) => { return ( <> ...

How can I disable auto-fill for password input fields? Setting autocomplete="off" doesn't seem to be working

Hey there, I'm having some trouble with the autocomplete feature in Google Chrome. Can anyone suggest an alternative way to disable autocomplete for password fields? By the way, my project is using Vue.js. ...

Unselected default option in Angular 4's select dropdown

My goal is to use Angular to retrieve a value from a variable and display it as the first option in a select element, while keeping the rest of the options below static. The issue I am facing is that even though Angular is fetching the data successfully, t ...

Potential Unresolved Promise Rejection (ID: 0): The object 'prevComponentInstance._currentElement' is undefined

Attempting to fetch JSON data in react native using axios.get(my_url_path), then updating the state with response.data under the key 'urldatabase'. When attempting to access this state key and read the data from the JSON, an error is encountered: ...

Is Moment.js displaying time incorrectly?

When using moment.tz to convert a specific date and time to UTC while considering the Europe/London timezone, there seems to be an issue. For example: moment.tz('2017-03-26T01:00:00', 'Europe/London').utc().format('YYYY-MM-DD[T]HH: ...

Managing browser navigation within a web application

I am currently developing a web-based application for internal use in the company I work for. The application is quite intricate, featuring numerous forms that will enable users to both view and input data, which will then be stored in a database upon savi ...

Error encountered in Next.JS when calling getInitialProps(ctx) due to undefined ctx variable

This is my code import NavLayout from "../../components/Navigation/Navigation"; export default function WorldOfWarcraft({ game }) { return (<NavLayout> {game.link} </NavLayout>) } WorldOfWarcraft.getInitialProps = as ...

Error: The node is unable to parse JSON data through the API

After loading a JSON file as a string, attempting to parse it back to JSON and send it as a response: router.get('/todos', (req,res) =>{ let todos = fs.readFile('todos.json', 'utf8',(err, data) =>{ if (err) ...

Storing notes using HTML5 local storage

I recently developed a unique note-taking web application where users can create multiple notes and switch between them using tabs on the left side. My next step was to implement local storage for saving these notes, so I inserted the following code: $(d ...