What is the best way to attach an EventListener to all DOM elements with a particular class?

Within my DOM, I have dynamically created spans that all have the class "foo".

Utilizing TypeScript, I aim to attach an onClick event to each of these spans post-creation.

Here is my current approach:

var foos = document.body.querySelectorAll(".foo");
foos.forEach(function (item) {            
    item.addEventListener("click", () => { 
        console.log(item); 
    });
});

However, I am facing an issue with running forEach on a NodeListOf.

Using foos = Array.from(foos) does not resolve the problem as it results in: 'from' doesn't exist on type 'ArrayConstructor'.

Answer №1

To simplify the process, utilize a basic for loop. Each element in the foos array can be accessed by index, allowing you to assign a click event to them. The reason for this is that querySelectorAll generates a NodeList, which is similar to an array in terms of indexing but does not have the same array methods available.

var foos = document.body.querySelectorAll(".foo"));
for(var i=0; i<foos.length; i++){
    foos[i].addEventListener("click", () => { 
        console.log(item); 
    });
});

Answer №2

Given that you've selected the jquery tag for your query, I'll present the jquery method:

$(".foo").on('click', function() { 
   // Implement your functionality here
}); 

Answer №3

I have devised three distinct approaches that you can utilize, each one being quite straightforward. Please take a moment to examine each code snippet to witness its functionality.

1 - The following example demonstrates how to attach the listener AFTER the creation of elements.

for (var i = 0; i < 4; i++){
  var a = document.createElement('input');
  a.type = 'button';
  a.value = 'click me ' + i;
  a.className = 'foo';
  document.body.append(a);
}

//JQUERY WAY
$('.foo').on('click', function(){
  console.log(this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

2 - This Example shows how to add the listener BEFORE the creation of elements.

//JQUERY WAY
$(document).on('click', '.foo', function(){
  console.log(this.value);
});

for (var i = 0; i < 4; i++){
  var a = document.createElement('input');
  a.type = 'button';
  a.value = 'click me ' + i;
  a.className = 'foo';
  document.body.append(a);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

3 - Finally, for those who prefer not to rely on jQuery, here is a Vanilla JS example:

for (var i = 0; i < 4; i++){
  var a = document.createElement('input');
  a.type = 'button';
  a.value = 'click me ' + i;
  a.className = 'foo';
  document.body.append(a);
}

//VANILLA JS WAY
var myElems = document.querySelectorAll('.foo');
myElems.forEach(function(elem){
  elem.onclick = function(){
    console.log(elem.value);
  }
});

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

Discovering when each iteration of a jQuery loop has finished

I am currently working on implementing the open graph API and incorporating a loop through a results callback. Ensuring that I can determine when the loop has finished in order to execute a 'success' function is proving to be challenging. Initi ...

When a .post() request receives a numerical response, it is increasing by a factor of 10

Currently, I am utilizing the Wordpress ajax api to transmit the output of a php function to the client through .post() ajax. The issue arises when the value returned includes an extra 0 alongside the actual numeric value. For instance, if the numeric valu ...

Express: utilizing rawBody or buffer for a specific endpoint

I am looking to access the rawBody (buffer) specifically for a POST request on one route within my application. Currently, I have the following code snippet in my app.js: app.use(bodyParser.json({ verify: function(req, res, buf) { req.rawBody = buf; }})) ...

What is the best way to distinguish if users are accessing my Facebook app through an iframe or by directly entering the

If my Twitter app url is http://tw.domain.com/ and the app url is http://apps.twitter.com/demoapp/ I need to ensure that users cannot access the application url directly, they must view it within an iframe on Twitter. What method can I use to detect & ...

WebApp specifically designed for iPads that mimics the functionality of a swipe

I am in the process of developing a full-screen web application for an iPad that will showcase a series of images in a slider format. The users should be able to swipe between the images and click on one to view it in detail. Below is an example showcasin ...

What is the process for changing the name of a key in a MongoDB response

I am reviewing the following code snippet: // retrieve a specific question app.get('/:id', (req, res) => { Question.findById(req.params.id, function(err, response){ if (err) { return res.status(404).send(); } ...

Assigning multiple identifiers to a single element

Multiple posts have emphasized the importance of using an ID only once. But, I'm facing a situation where I need to pass 2 PHP variables to my JavaScript. I initially thought of using document.getElementById, but since IDs must be unique, this approa ...

Implementing Shader Effects around Mouse using Three.js

Could someone please share tips on how to add a shader effect around the mouse area using Three.js? I'm inspired by the homepage of this website: I'm eager to explore some leads or examples. Thank you in advance! ...

Implementing Twain functionality in an Electron-based desktop application

I've been tasked with building a desktop application using React + Electron, and my client wants to incorporate scanning documents using a scanner and uploading them to the server through the app. Are there any effective ways to integrate Twain into R ...

Pause and check for the completion of data loading in mapstate

I have a stored userProfile in the Vuex state in order to access it throughout my project. However, when I try to use it in the created() hook, the profile is not loaded yet during the initial page load. Although the object exists, it does not contain any ...

Can a Bluetooth speaker in a car be utilized for noise cancellation?

While using my ANC earphones one day, I had a thought. The earphones were nearly able to drown out the noise of the car. This got me thinking: could ANC technology be used with car speakers and mobile phone apps? Although it might be challenging to resp ...

Using Express to Deliver Static Content to Subdirectories

I am currently using Express to serve a React application that was bootstrapped with Create React App. The project has the following directory structure: |--client/ | |--build/ | | |--static/ | | | |--main.css | | | |--main.js | ...

Laravel Mix fails to recognize VueJs integration in Laravel

Having an issue setting up VueJs with laravel 5.7 and mix where it keeps saying VueJs is not detected. I've already executed the npm install command. Below is my welcome view: <!doctype html> <html lang="{{ str_replace('_', '- ...

What is the best way to extract the JSON data from a client-side GET request response?

Here is my request from the client side to the server in order to retrieve JSON data. fetch("/" + "?foo=bar", { method: "GET", }).then(response => { console.log(" ...

Variable not accessible in a Typescript forEach loop

I am facing an issue with a foreach loop in my code. I have a new temp array created within the loop, followed by a nested foreach loop. However, when trying to access the temp array inside the nested loop, I encounter a "variable not available" error. le ...

Node.js and EJS are throwing an error, indicating that the file.ejs is unable to identify the variable definitions

I am facing an issue with my express.js server template. A 'x is not defined' error keeps popping up, but I can't seem to find where the problem lies. I even checked a friend's code from the same tutorial, and it works on his machine. ...

Creating a database using Angular2+ in CouchDB can be achieved by following these steps

I have been attempting to set up a database in couchdb using angular2+. My goal is to create a button that, when clicked, will initiate the creation of the database. However, I keep encountering an error message. "ERROR Error: Uncaught (in promise): H ...

Has the user successfully authenticated with Google?

Possible Repetition: How to verify if a user is logged into their Google account using API? I'm working on a website that displays a Google Calendar. My query is: Can I determine whether a user is currently logged into a Google Account? If it&ap ...

How can I automatically direct my NodeJS application to the login screen?

Here is the setup of my project structure: There is a simple folder called static, within which I have: index.html (the homepage for user registration) login.html (the login page) In the parent folder, there is a file named server.js: // NodeJS code for ...

Saving a single ID at a time in a UseState array by clicking in ReactJS

When clicking on the "click here" button, I am trying to save favorite post IDs in an array. However, the issue is that it is currently only saving one ID at a time in the array. Every time you click on another "click here" button, it removes the previous ...