Adding anonymous handlers in a loop in JavaScript

Anonymous functions can also be used as handlers added in a loop. This makes the code more compact and saves us from having to come up with a name for a function that is only used in one place.

Let's add anonymous handlers to elements:

let elems = document.querySelectorAll('p'); for (let elem of elems) { elem.addEventListener('click', function() { console.log(this.textContent); }); }

Given the following code:

<div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> let divs = document.querySelectorAll('div'); for (let div of divs) { div.addEventListener('click', func); } function func() { this.textContent++; }

Make the handler function anonymous.

enru