I'm struggling to activate the eventListener on several elements with the same className or ID. Unfortunately, only the initial child is being triggered in my current code implementation

Hello fellow developers, I'm facing an issue while working on a project. I have about ten menu items with the same ID, and I want to be able to edit each one when it is clicked. Here's what I tried using JavaScript:

    
    const menuElement = document.querySelector('#menuElement')
    const darktheme = document.querySelector('.dark')

    loadEventListener()
    
    function loadEventListener() {
        menuElement.addEventListener('click', draw)
    }

    function draw() {
        menuElement.style.background = 'var(--primary-color)'
    }

However, only the first menu element responds when clicked, but not the rest of them.

Any help would be greatly appreciated. Thank you!

Answer №1

Indeed. Rather than adding multiple event listeners to each element individually, consider utilizing "Event Delegation". By attaching a single event listener to a common ancestor element and allowing the event to bubble up to that ancestor, you can streamline your code. Within the event callback function, you can then determine if the event originated from a specific element that requires handling, and proceed accordingly.

It's important to remember that while ids must be unique, multiple elements can share the same class, making it a practical choice for this purpose.

Here is an EXAMPLE:

// Set up an event handler on a common ancestor
document.addEventListener("click", function(event){
  // Check to see if the event originated at an element with the "foo" class
  if(event.target.classList.contains("foo")){
    // Handle the event any way you want
    event.target.classList.add("bold");
  }
});
.bold { font-weight:bold; }
<p>Click on any of the lines. Only the ones with the "foo" class will get bolded.</p>
<div class="foo">XYZ</div>
<div class="fooBar">XYZ</div>
<div class="foo">XYZ</div>
<div class="fooBar">XYZ</div>
<div class="foo">XYZ</div>
<div class="fooBar">XYZ</div>

Answer №2

To select all elements in the document that match a CSS selector, you can utilize the querySelectorAll() method. Once you have obtained a NodeList of these elements, you can then use the forEach() method to add event listeners to each element individually.

Here is a simple example to demonstrate this:

window.addEventListener("DOMContentLoaded", e => {
  document.querySelectorAll(".myclass").forEach((element, i) => {
    element.addEventListener("click", () => console.log(`Div ${i} was clicked.`))
  });
})
.myclass {
  border: 1px solid black;
  padding: 10px;
  margin: 5px;
}
<div class="myclass">Div 0</div>
<div class="myclass">Div 1</div>
<div class="myclass">Div 2</div>
It's important to wait for the DOM to be fully loaded before attaching event handlers using the DOMContentLoaded event.

Remember, IDs must be unique so do not use an ID for this purpose!

Another approach to achieve this functionality is by utilizing event delegation, as explained in Scott Marcus's solution.

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

Iterating through elements within a Div will retrieve the initial element exclusively

Is there a way to loop through all elements within the MainDiv Div in order to retrieve their values? Currently, I am only able to retrieve the value of the first element. <div id="MainDiv"> <input type="text" id="MyText"value="Text1" /> ...

An issue has been discovered with the Search function as JavaScript's Array.filter() and .map() methods are not functioning properly, resulting in

Currently, I'm working on integrating a search feature into my Flask application that will display the cities entered by users and are present in the JSON API results of a weather API. I am following a tutorial and have used a code similar to this: h ...

Angular login/signup modal/dialog component for seamless user authentication

Currently, I am working on adding a login/signin dialog to my app similar to the one used by Medium. After doing extensive research online, I have decided to use the $modal from angular ui-bootstrap for this. Can anyone please recommend a tutorial that wil ...

Having trouble getting my list items to display on individual lines within the foreach loop. It just doesn't seem to be working as expected

In the event listener, I need to ensure that my list items within the forEach loop are not displaying on separate lines. This issue is causing a problem in a lengthy section of code. The goal is to update questions when an answer is clicked from a list. B ...

Guide to designing a CSS gradient with a downward arrow linked to a specific container

I'm attempting to add a triangular arrow beneath the v-container, complete with a gradient color scheme. However, I'm struggling to integrate the gradient seamlessly. If I use CSS to create the arrow, the gradient doesn't align correctly. ...

The function for utilizing useState with a callback is throwing an error stating "Type does not have

Currently, I am implementing the use of useState with a callback function: interface Props { label: string; key: string; } const [state, setState] = useState<Props[]>([]); setState((prev: Props[]) => [...pr ...

Node.js - Creating seamless integration between Sequelize model JS and controller TS

Having trouble making my User.js model recognized inside my UserController.ts with sequelize in TypeScript. Edit: Unable to change the file extensions for these files. In the await User.findAll() part, an error occurs when running on the server, stating ...

Problems with the main title formatting in the header

I am currently working on a new website and have encountered an issue with the header design. The Mainline "PersIntra" is overlapping the "log out button" box, which I would like to be positioned beside it instead. Despite my efforts with CSS and nesting ...

Iterate over a JSON document, insert an item, and then store the updated data in a separate

My JSON file contains elements like this: var data=[{ "Name": "Jeff", "Age": 35 }, { "Name": "cliff", "Age": 56 }] I need to include a new field called 'Country'. So the updated structure should be: var data=[{ "Name": "Jef ...

Enhancing OpenSeadragon images with custom overlays and managing error messages

Currently, I am experimenting with the Basic Single-Row Tile Source Collection example using the same configurations and tile sources outlined in the example. However, I am encountering difficulties in adding overlays to the first and second images as int ...

Unable to get the onchange event to trigger for a span element

Is there a way to trigger the onchange event on a span element that doesn't seem to be working? Here is the code I am using: Attempt 1 document.getElementById(seconds).addEventListener('change', (event: MutationEvent & { path: any }) =& ...

Instructions on creating a "ripple" effect on a webpage using CSS

I am attempting to create a wavy border effect where two sections meet on a page (refer to the image below). What is the most effective way to achieve this? The waves should be uniform in size. EDIT: To whoever flagged this as 'already answered' ...

Verify the presence of a ::after pseudo-element on a scraped webpage

I am facing a dilemma with a checkbox on my website that is described in the following HTML code: html = <div class="checkbox checkbox-success checkbox-block"> <input type="checkbox" data-false-value="'0'&qu ...

Step-by-step guide on setting up a click counter that securely stores data in a text file, even after the

Can anyone help me make this link actually function as intended? Right now it only runs the JavaScript code, but I would like it to run the code and redirect to a webpage. Additionally, I need the data to be saved to a text file. Please provide assistanc ...

Is it possible to include jQuery's selectors contain and closest within my CSS selector?

I created a script to hide specific table rows as follows: $('.ms-formtable nobr:contains("Question")').closest('tr').hide(); However, I'm unsure if there is a way to achieve the same result using only CSS. Can anyone provide adv ...

Problems with implementing JavaScript code in a WebView

I am currently working on an android WebView project where I have managed to change the background color to orange with this code snippet. @Override public void onPageFinished(WebView view, String url) { wv.loadUrl("jav ...

What are the ways to convert canvas animations into gif or webm formats?

I've written a function to capture each frame for the GIF, but I'm experiencing laggy output and crashes as the data increases. Any recommendations? function generateGifFromImages(imageList, frameRate, fileName, scaling) { gifshot.createGIF({ ...

issue with border color staying the same when focusing

I've been struggling with changing the border on focus in my code. Despite trying various methods, nothing seems to be working. Can someone help me figure out what I'm doing wrong? <input type="text" spellcheck="false" data-placement="top" id ...

Organize the array following the guidelines of a card game with a versatile approach

deck = ['Jack', 8, 2, 6, 'King', 5, 3, 'Queen', "Jack", "Queen", "King"] <!- Desired Result = [2,3,5,6,8,'Jack','Queen','King'] Explore the challenge: Arrange the ...

Cannot access mobile navigation due to expanded browser search bar

Greetings, all! Currently, as I am in the process of developing a website for my company, I have encountered an issue with the navigation menu, specifically on mobile devices, or more accurately, mobile browsers(most of them). The hamburger icon seems to ...