0

ok, see this code

<p>This is question 1.</p>

<img src="http://cliparts.co/cliparts/qTB/5yd/qTB5ydpzc.gif" alt="show answer" height="42" width="42"  onclick="toggleAnswer(1)">

<p id="1">This answer1.</p>

<p>This is question 2.</p>

<img src="http://cliparts.co/cliparts/qTB/5yd/qTB5ydpzc.gif" alt="show answer" height="42" width="42"  onclick="toggleAnswer(2)">

<p id="2">This answer2.</p>

<script type="text/javascript">

function toggleAnswer(no){
        if (document.getElementById(no).style.display=="none")
        {
          document.getElementById(no).style.display="block";
        }
        else
        {
          document.getElementById(no).style.display="none";
        }
 }    

   </script>  

The code means that there are many questions and if we click on the image next to a specific question the answer will appear accordingly.

Now, I want to make a button "show All" & "close ALL". WHen people click "show All" it will show all answers and when clicking "close ALL", it will close all answers.

My question is that

Is there anyway to force all elements inside a page to have style of either "block" or "none" without going through a loop?

Tom
  • 825
  • 1
  • 8
  • 28

1 Answers1

1

You can use a CSS class on a parent element: https://jsfiddle.net/ckyoxobp/

HTML

<div id="questions">
    <button id="toggle">Show all answers</button>
    <p>This is question 1.</p>
    <img src="http://cliparts.co/cliparts/qTB/5yd/qTB5ydpzc.gif" alt="show answer" height="42" width="42">
    <p id="1" class="answer">This answer1.</p>
    <p>This is question 2.</p>
    <img src="http://cliparts.co/cliparts/qTB/5yd/qTB5ydpzc.gif" alt="show answer" height="42" width="42">
    <p id="2" class="answer">This answer2.</p>
</div>

JS

var questions = document.getElementById('questions');
var toggle = document.getElementById('toggle');

function toggleAll() {
  if (questions.classList.contains('show-all')) {
    questions.classList.remove('show-all');
    toggle.innerText = 'Show all answers';
  } else {
    questions.classList.add('show-all');
    toggle.innerText = 'Hide all answers';
  }
}

toggle.onclick = toggleAll;

CSS

#questions .answer {
  display: none;
}

#questions.show-all .answer {
  display: block;
}

UPDATE

I should have been more explicit about browser compatibility; I simply wanted to show an example of using a class on a parent element. Element.classList isn't supported in some versions of some browsers, notably IE9 and earlier, and IE10 has limit limited support of it. However, Element.className has near-complete coverage.

Modifying an element's classes is beyond the scope of this question, but this answer to a different question will give you a good start.

Community
  • 1
  • 1
jpo
  • 21
  • 3