Many elements with show buttons in JavaScript
Let now we have a lot of paragraphs and each has its own button to hide:
<p>1</p><button>toggle</button>
<p>2</p><button>toggle</button>
<p>3</p><button>toggle</button>
Let's make it so that clicking on the button hides or shows the paragraph corresponding to it.
To do this, we somehow need to associate the buttons with our paragraphs. There are several ways to do this.
First way
Let's link buttons and paragraphs as follows:
<p id="elem1">1</p><button data-elem="elem1">toggle</button>
<p id="elem2">2</p><button data-elem="elem2">toggle</button>
<p id="elem3">3</p><button data-elem="elem3">toggle</button>
Now, by clicking on any button, we will read the contents of its data-elem attribute and look for a paragraph with that id. We'll toggle it. Let's implement the described:
let buttons = document.querySelectorAll('button');
for (let button of buttons) {
button.addEventListener('click', function() {
let elem = document.querySelector('#' + this.dataset.elem);
elem.classList.toggle('hidden');
});
}
Study my solution, and then independently, without looking at my code, solve this problem.
Second way
It is not very convenient to arrange id and data attributes. Let's make it so that the relationship is by ordinal number: let the first button hide the first paragraph, the second button - the second and so on.
Let's implement the described:
let buttons = document.querySelectorAll('button');
let elems = document.querySelectorAll('p');
for (let i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', function() {
elems[i].classList.toggle('hidden');
});
}
Study my solution, and then independently, without looking at my code, solve this problem.
Third way
As you can see, the paragraph associated with a button is its left neighbor. This can be used as a link:
let buttons = document.querySelectorAll('button');
for (let button of buttons) {
button.addEventListener('click', function() {
this.previousElementSibling.classList.toggle('hidden');
});
}
Study my solution, and then independently, without looking at my code, solve this problem.