I\'m guessing I have a basic error in thinking but I just can\'t get around it.
I have a couple of text fields which I want to add an EventListener to. I put them all i
If you want to attach an event to several elements without an explicit loop, you can use a helper function:
function attachEvents(elementList, eventName, handlerFunction) {
if(typeof elementList == "string")
elementList = document.querySelectorAll(elementList);
for(var i = 0; i < elementList.length; i++)
elementList[i].addEventListener(eventName, handlerFunction);
}
You call it like this:
attachEvents("#area button", "click", function(event) {
this.style.backgroundColor = "red";
});
Or like this:
attachEvents(document.getElementById("area").getElementsByTagName("button"), "click", function(event) {
this.style.backgroundColor = "red";
});
You don't always want document.querySelectorAll
- doing it yourself means you also do things like some_element.querySelectorAll
which is really nice when working with things that aren't yet part of the document, or have no unique selector.
But regardless, putting the loop in a helper function gives you that jquery-esque one-liner without a huge library, it is just a few lines of simple code.