Adding click event listener to elements with the same class
You should use querySelectorAll
. It returns NodeList, however querySelector
returns only the first found element:
var deleteLink = document.querySelectorAll('.delete');
Then you would loop:
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();
}
});
}
Also you should preventDefault only if confirm === false
.
It's also worth noting that return false/true
is only useful for event handlers bound with onclick = function() {...}
. For addEventListening
you should use event.preventDefault()
.
Demo: http://jsfiddle.net/Rc7jL/3/
ES6 version
You can make it a little cleaner (and safer closure-in-loop wise) by using Array.prototype.forEach iteration instead of for-loop:
var deleteLinks = document.querySelectorAll('.delete');
Array.from(deleteLinks).forEach(link => {
link.addEventListener('click', function(event) {
if (!confirm(`sure u want to delete ${this.title}`)) {
event.preventDefault();
}
});
});
Example above uses Array.from and template strings from ES2015 standard.
The problem with using querySelectorAll
and a for
loop is that it creates a whole new event handler for each element in the array.
Sometimes that is exactly what you want. But if you have many elements, it may be more efficient to create a single event handler and attach it to a container element. You can then use event.target
to refer to the specific element which triggered the event:
document.body.addEventListener("click", function (event) {
if (event.target.classList.contains("delete")) {
var title = event.target.getAttribute("title");
if (!confirm("sure u want to delete " + title)) {
event.preventDefault();
}
}
});
In this example we only create one event handler which is attached to the body
element. Whenever an element inside the body
is clicked, the click
event bubbles up to our event handler.