


How to Add Click Event Listeners to Multiple Elements with the Same Class?
Nov 09, 2024 pm 04:30 PMAdding Click Event Listeners to Elements with the Same Class
In this scenario, you have a list view for deleting IDs and want to add a confirmation alert to all elements with the class "delete." However, you've encountered an issue where only the first element with the class seems to receive the listener.
Solution
To resolve this, you need to use querySelectorAll instead of querySelector. querySelectorAll returns a NodeList containing all elements with the specified class:
var deleteLink = document.querySelectorAll('.delete');
Now, you can iterate through the NodeList and add event listeners to each element:
for (var i = 0; i < deleteLink.length; i++) { deleteLink[i].addEventListener('click', function(event) { if (!confirm("sure u want to delete " + this.title)) { event.preventDefault(); } }); }
Additionally, only prevent the default action if the user does not confirm the deletion. This ensures that the deletion is only executed if the user explicitly chooses to proceed.
ES6 Enhancements
Using ES6, you can simplify the loop using Array.prototype.forEach:
Array.from(deleteLinks).forEach(link => { link.addEventListener('click', event => { if (!confirm(`sure u want to delete ${this.title}`)) { event.preventDefault(); } }); });
This version utilizes template strings (introduced in ES2015) for a cleaner syntax.
The above is the detailed content of How to Add Click Event Listeners to Multiple Elements with the Same Class?. For more information, please follow other related articles on the PHP Chinese website!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Replace String Characters in JavaScript

Custom Google Search API Setup Tutorial

8 Stunning jQuery Page Layout Plugins

Improve Your jQuery Knowledge with the Source Viewer

10 Mobile Cheat Sheets for Mobile Development
