Attach event listeners to every item within a NodeList

How can I add an event listener to each element in a NodeList?

var items = document.getElementsByClassName('productLnk');

function myFunction(element, index, array) {
    element.addEventListener('click', function() {
        alert('Hello!');
    });
}

Array.prototype.forEach.call(items, myFunction);

However, I am getting an error that says "test.forEach is not a function". How can I resolve this issue?

Answer №1

To iterate through a NodeList, you can convert it to an Array using the Array#forEach method. In ES6, you can use Array.from.

Array.from(test).forEach(theTest)

If you are working with older browsers, you can also use Array#slice along with Function#apply or Function#call.

[].slice.call(test).forEach(theTest)

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

Troubleshooting Vue.js Error: Uncaught ReferenceError - jQuery Undefined

I'm a beginner with Vue.js and I'm attempting to develop a custom component that utilizes the jQuery formBuilder plugin from formBuilder. However, when I try to include this component file within another component, an error occurs: Uncaught Re ...

Anti-virus programs are preventing long-standing AJAX connections

Hey there, I have come across something quite strange while developing a web application that relies on long-held HTTP connections using COMET to stream data between the server and the application. The issue I've encountered is that some anti-virus p ...

Managing Arrays within Arrays in Postgresql

I successfully extracted an array from a JSONB data type in PostgresQL 10.5 using the query below, which returned the array as text (visible in the column header). The parent data table includes a JSONB column. This code extracts array-text from the JSON ...

How to Apply a CSS Class to the Body Tag in Angular 2.x

How can I add [class.fixed]="isFixed" to the body tag when Angular 2.x is bootstrapped inside the body (outside my-app)? <html> <head> </head> <body [class.fixed]="isFixed"> <my-app>Loading...</my-app> </body> & ...

Utilizing Animate Function in Framer Motion for Object Animation

I am currently experimenting with the Framer Motion library in an attempt to create interactive movement for objects when they are clicked. My goal is to be able to relocate a component to a specific destination regardless of its initial position. I'm ...

Hide the scrollbars on the sidebar

I'm attempting to recreate a sleek scrollbar that caught my eye on the website . To achieve this, I need to have a screen larger than 955px in order to display the sidebar. However, when my sidebar overflows in the y direction, it causes an additional ...

Tips for Utilizing PHP Without the Need to Refresh the Page

Below are the contents of three files with their respective code: Controler.php <iframe id="frame1" style="display:none"></iframe> <iframe id="frame2" style="display:none"></iframe> <button onClick="document.getElementById(&apo ...

Allow editing for only a specific part of a text box

Creating a customized personal URL page for users on my site is important to me. I envision the value of a text box being "example.com/username," with the "example.com/" part displayed in the text box, but not editable. I've noticed that Tumblr accom ...

Unable to cut a line shape in Three.js using THREE.ExtrudeGeometry for punching

Hey everyone, I'm brand new to Three.js I'm looking to cut out some shapes from a flat board using THREE.ExtrudeGeometry. Check out the code snippet below: // Code snippet here... In my example, I've included a circular shape and t ...

Combine various arrays into a single table

<table border="2"> <?php foreach($array1 as $value) { echo '<tr><td>'; echo $value; echo '</td></tr>'; } ?> </table> I have more array: array2,array3. The above code only executes ...

Tips for avoiding a button reverting to its original state upon page refresh

I have a button with the ID #first that, when clicked, is replaced by another button with the ID #second. However, if I refresh the page after clicking on the second button, it goes back to displaying the first button. Is there a way to make sure that th ...

What is the best way to enhance the capabilities of a current tinyMCE button?

I am interested in enhancing the capabilities of the default buttons in tinyMCE by adding additional functionality. I'm curious to know how this can be achieved. For instance, If I would like the paste button not only to paste content, but also perf ...

What is the best way to create multiple AngularJS applications using NodeJS?

Upon completing the tutorial found at https://docs.angularjs.org/tutorial, I was inspired to create a new application on my local machine using AngularJS and NodeJS as the server. To start this new project, I made a separate folder at the same level as th ...

AngularJS anticipates the completion of a lone asynchronous request

Attempting to assign data to the scope after an asynchronous call. There is an array named companies in the factory. factory.getByCategoryId = function (id) { $http.get('http://localhost/campaign?access-token=12345&id=2').then( func ...

disable the react .hover behavior once clicked

Can someone help me figure out why my attempt to cancel the .hover on function using .off is not working? $("document").ready(function(){ $("button").hover(function(){ $("h1").hide(); }, function(){ ...

Quickly determine the value of an individual unchecked item in a group of checkboxes when it is changed

Is there a way to retrieve the value of an unchecked checkbox immediately after it is un-checked? I only want to capture the value of the checkbox that was just un-checked, not all un-checked checkboxes. $('input:checkbox[name=vehicle]').on("c ...

How to determine if a string includes a particular substring in Javascript without using the indexOf method

Is it possible to determine if a string contains a specific substring without using indexOf, regex match, or any standard JavaScript methods? Feel free to review this code snippet on jsfiddle: https://jsfiddle.net/09x4Lpj2/ var string1 = 'applegat ...

Ways to eliminate redundant values in an associative array

I am working with an associative array and need to remove duplicate values that have appeared first. For example, if DC-30 is the first appearance, I want to remove all instances of DC-30 in the array. Similarly, if HSD-M has already appeared, I want to re ...

`The Problem with the DataTables Button plugin`

I've set up a dynamic table using DataTables, and everything seems to be working fine with the DataTable plugin. However, I recently discovered the Button datatable plugin, which allows for exporting table data as PDF, CSV, etc. I tried to integrate ...

Bespoke search functionality using AJAX and tags in WordPress

I have created a custom search form in my WordPress theme that looks like this: <form role="search" class="form" method="get" action="<?php echo home_url('/');?>"> <input type="search" id="keyword" class="inp-search" onclick="sh ...