Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
46
rated 0 times [  49] [ 3]  / answers: 1 / hits: 10217  / 3 Years ago, thu, october 7, 2021, 12:00:00

I'm trying to toggle text showing when I click a button for each item I have in a Carousel.


When I use "getElementByID" it works fine, but I need to use "getElementsByClassName" because it's a repeater field in the backend and there are several buttons in the whole carousel.


Anyway here is my code -


 function toggleText(){
var x = document.getElementsByClassName("figure-caption-test");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}

<button class="figure-button" id="figure-button" onclick="toggleText()">
REVEAL ANSWER
</button>

<figcaption class="figure-caption-test" id="reveal-text" style="display: none;">
Text that appears
</figcaption>

And the error i'm getting is -
Cannot read properties of undefined (reading 'display')


Any help is greatly appreciated, thanks


More From » button

 Answers
1

getElementsByClassName returns array of elements.
this is my solution:




 function toggleText(){
var elms = document.getElementsByClassName(figure-caption-test);

Array.from(elms).forEach((x) => {
if (x.style.display === none) {
x.style.display = block;
} else {
x.style.display = none;
}
})
}

<button class=figure-button id=figure-button onclick=toggleText()>
REVEAL ANSWER
</button>

<figcaption class=figure-caption-test id=reveal-text style=display: none;>
Text that appears
</figcaption>




[#796] Monday, September 27, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
turnerf

Total Points: 620
Total Questions: 101
Total Answers: 109

Location: French Polynesia
Member since Tue, Jul 7, 2020
4 Years ago
turnerf questions
;