Search code examples
javascripthtmlhide

Hiding elements of li by its class using JavaScript


I have many li with their class as ans in ul tag. When clicked in hide button I want to disappear those li having ans as class and when clicked show button I want all them to be reappeared with little transition if possible.

I have done little JavaScript but it is hiding only first position li and and it is not affecting other li. and I've no idea how to reappear those.

My HTML:

<ul>
    <li class="one">Lorem ipsum dolor sit amet.</li>
    <li class="ans">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cum?</li>
    <hr>
    <li class="two">Lorem, ipsum.</li>
    <li class="ans">Lorem ipsum dolor sit amet consectetur adipisicing elit.</li>
    <hr>
    <li class="three">Lorem ipsum dolor sit.</li>
    <li class="ans">Lorem ipsum dolor sit amet consectetur adipisicing elit.</li>
</ul>

<div class="btn" style="text-align: center;">
                <button class="green" type="button">Show Answer</button>
                <button class="red" type="button">Hide Answer</button>
              </div>

Some JavaScript I did:

<script>
        document.getElementsByClassName("red")[0].addEventListener("click", closeBox);
function closeBox(){
  document.getElementsByClassName("ans")[0].style.display = "none";
}
        </script>

I would prefer to use JavaScript, I don't want jQuery.


Solution

  • So technically the first issue is that you are trying to access only the first element what getElementsByClassName found for you. You need iterate through all the elements by using Array.prototype.forEach.call which will help you to toggle visibility for the li items.

    So based on that I think you can do something like this:

    document.getElementsByClassName("red")[0].addEventListener("click", () => setVisiblity(false));
    document.getElementsByClassName("green")[0].addEventListener("click", () => setVisiblity(true));
    
    const setVisiblity = (visible) => {
      const ansElements = document.getElementsByClassName('ans');
      const style = visible ? 'list-item' : 'none';
    
      Array.prototype.forEach.call(ansElements, e => {
        e.style.display = style;
      });
    }
    <ul>
      <li class="one">Lorem ipsum dolor sit amet.</li>
      <li class="ans">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cum?</li>
      <hr>
        <li class="two">Lorem, ipsum.</li>
        <li class="ans">Lorem ipsum dolor sit amet consectetur adipisicing elit.</li>
      <hr>
      <li class="three">Lorem ipsum dolor sit.</li>
      <li class="ans">Lorem ipsum dolor sit amet consectetur adipisicing elit.</li>
    </ul>
    
    <div class="btn" style="text-align: center;">
      <button class="green" type="button">Show Answer</button>
      <button class="red" type="button">Hide Answer</button>
    </div>

    Additionally I agree, jQuery for this small code solution would be totally overkill.

    I hope this helps!