Suppose we have paragraphs and a button:
<p>aaa</p>
<p>bbb</p>
<p>ccc</p>
<p>ddd</p>
<p>eee</p>
<button>click me</button>
Let the user click on these paragraphs
randomly. Let's make it so that when
the button is clicked, an exclamation
mark is added to the end of each clicked
paragraph. Let's solve the problem with
Set
.
Let's get started. First, let's get our elements into variables:
let button = document.querySelector('button');
let elems = document.querySelectorAll('p');
Let's create a new Set
collection:
let set = new Set;
Then we go through the paragraphs in a loop and hang a click handler on them:
for (let elem of elems) {
elem.addEventListener('click', function() {
});
}
Let's now click on a paragraph and add this paragraph to the collection:
for (let elem of elems) {
elem.addEventListener('click', function() {
set.add(this);
});
}
Due to the fact that we use the Set
collection, clicking on the paragraph again
will not add a duplicate paragraph.
Let's now, on click on the button, iterate over the contents of our collection and add an exclamation mark to the end of each paragraph:
button.addEventListener('click', function() {
for (let elem of set) {
elem.textContent = elem.textContent + '!';
}
});
Given paragraphs and a button. The user clicks on these paragraphs randomly. Make it so that when you click on the button, an exclamation mark is added to the end of each paragraph that was clicked.