Unbinding event handlers in a loop in JavaScript

Let now we have not single element, but several. For example, a few paragraphs:

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

Let's bind the function func as click handler to each of these paragraphs:

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

Let's now rewrite the code so that each paragraph only responds to the first click on it. To do this, when clicking on a paragraph, we will unbind the attached handler from it. In this case, the unbinding will be specifically from this paragraph, without affecting the rest.

As you already know, the element in which the event occurred can be accessed in the handler function via this. This means that you need to unbind the handler from this, like this:

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

Given paragraphs. By clicking on any of the paragraphs, add an exclamation mark to the end of it. Make it so that this addition occurs only on the first click.

enru