Adding handlers in a loop in JavaScript

Let's now learn how to bulk add event handlers to elements. Let, for example, we have paragraphs:

<p>text1</p> <p>text2</p> <p>text3</p>

Let's also have a function:

function func() { console.log('!'); }

Let's iterate over our paragraphs in a loop and add the function func as a click handler to each paragraph:

let elems = document.querySelectorAll('p'); for (let elem of elems) { elem.addEventListener('click', func); }

Let's go ahead and make it so that when you click on any paragraph, the text of this paragraph is displayed. There is, however, a problem: there are many paragraphs, and there is only one handler function. How do we distinguish our paragraphs inside the handler function?

The this object will help us with it - when the function is called at the time of the event, this object will point to the element where this event happened. Let's rewrite the code of our function func in accordance with the above:

function func() { console.log(this.textContent); // outputs the paragraph text }

Given the following function:

function func() { this.value = Number(this.value) + 1; }

Inputs are also given. Make it so that on loss of focus in any of our inputs, the above function is executed.

Given paragraphs with numbers. Make it so that when you click on any paragraph, its number in it is squared.

enru