Does NodeList support addEventListener. If not what is the best way to add EventListener to all the nodes of the NodeList. Currently I am using the code snippet as show be
The simplest example is to add this functionality to NodeList
NodeList.prototype.addEventListener = function (event_name, callback, useCapture)
{
for (var i = 0; i < this.length; i++)
{
this[i].addEventListener(event_name, callback, useCapture);
}
};
Now you can do:
document.querySelectorAll(".my-button").addEventListener("click", function ()
{
alert("Hi");
});
In the same way, you can do a forEach loop
NodeList.prototype.forEach = function (callback)
{
for (var i = 0; i < this.length; i++)
{
callback(this[i], i);
}
};
Using:
document.querySelectorAll(".buttons").forEach(function (element, id)
{
input.addEventListener("change", function ()
{
alert("button: " + id);
});
});
EDIT : note that NodeList.prototype.forEach has existed ever since november 2016 in FF. No IE support though