I want to add more "read more" buttons, but every response only for 1st one. Buttons open only first element.
I tried some versions with querySelectorAll but I can’t figure that out unfortunately…
How can I resolve this?
function myFunction() {
const dots = document.getElementById("dots");
const moreText = document.getElementById("more");
const btnText = document.getElementById("myBtn");
if (dots.style.display === "none") {
dots.style.display = "inline";
btnText.innerHTML = "Przeczytaj więcej";
moreText.style.display = "none";
} else {
dots.style.display = "none";
btnText.innerHTML = "Zwiń";
moreText.style.display = "inline";
}
}
<div class="quote__box__text">
lorem ipsum <span id="dots">...</span>
<span id="more" Lorem ipsum</span>
<button onclick="myFunction()" id="myBtn">Read more</button>
</div>
<div class="quote__box__text">
lorem ipsum <span id="dots">...</span>
<span id="more" Lorem ipsum</span>
<button onclick="myFunction()" id="myBtn">Read more</button>
</div>
2
Answers
As per my comment, ids should be unique – instead use classes and then you can bind the click to each button and get the elements based on the clicked element
Your HTML is invalid, you can’t use the same
id
on more than one element. Use a class instead, and hook up the handler dynamically. Then, in the click handler, use the specific button that was clicked to find the elements in that samediv
that you want to change. I also strongly recommend using classes rather than inline styles.For instance:
In that example, see how the CSS classes and structure drive the hiding and display of the elements.
We could change the button text in a similar way if we want; I’ll leave that as an exercise for the reader. 🙂 (Hint: Use elements inline the
button
you show/hide.)More to explore:
querySelectorAll
addEventListener
currentTarget
closest
classList