function MyFunction(){
let x = document.getElementsByClassName("one");
for(i=0; i<x.length; i++){
if (x[i].style.display === "block") {
x[i].style.display = "none";
} else {
x[i].style.display = "block";
}
}
};
.one{
display: none;
}
<h1>Testing</h1>
<div class="one">
<p>Some text</p>
</div>
<button onclick="MyFunction()">Show more!</button>
</div>
<div>
<h1>Testing</h1>
<div class="one">
<p>Some other text</p>
</div>
<button onclick="MyFunction()">Show more!</button>
</div>
I´m wondering based on the code below, how i can make a function the best way that i can use on my button to show content on for each element in the class one array if that makes sense? Now when i press it shows content for all the divs and i just want to show for the one in wich my button belongs.
I´ve tried to make a class for buttons and loop through them as well but i simply dont understand how to do this.
>Solution :
You could loop over all the buttons, attach an event listener to each one, and toggle the visibility of the element with the class 'one' in the parent of the button in the event handler.
document.querySelectorAll('.open-btn').forEach(btn =>
btn.addEventListener('click', e => {
btn.parentElement.querySelector('.one').classList.toggle('hide');
})
);
.hide {
display: none;
}
<div>
<h1>Testing</h1>
<div class="one hide">
<p>Some text</p>
</div>
<button class="open-btn">Show more!</button>
</div>
<div>
<h1>Testing</h1>
<div class="one hide">
<p>Some other text</p>
</div>
<button class="open-btn">Show more!</button>
</div>
Alternatively, you can use event delegation and only attach the event listener to the closest static ancestor. (document is used here as an example, but you should choose a closer static ancestor.)
document.addEventListener('click', e => {
if (e.target.matches('.open-btn')) {
e.target.parentElement.querySelector('.one').classList.toggle('hide');
}
});
.hide {
display: none;
}
<div>
<h1>Testing</h1>
<div class="one hide">
<p>Some text</p>
</div>
<button class="open-btn">Show more!</button>
</div>
<div>
<h1>Testing</h1>
<div class="one hide">
<p>Some other text</p>
</div>
<button class="open-btn">Show more!</button>
</div>