How to hide/show my HTML elements?

Asked

Viewed 164 times

1

<ul>
    <li onclick="mostrar('img')">
        PASTA - Fotos
        <ul>
            <li id="img" style="display: none;">Imagem1.jpg</li>
            <li id="img2" style="display: block;"> Imagem2.jpg </li>
        </ul>
    </li><br>
    <li> PASTA - BOLETOS
        <ul>
            <li id="boleto">boleto.pdf</li>
        </ul>
    </li>
</ul>


<script>
function mostrar(){
    let show = document.getElementById('img')
    if(show.style.display == 'none'){
        show.style.display = 'block'
    }
    else{
        show.style.display = 'none'
    }
}

</script>

I am studying and decided to test the logic of a common Folder of a computer.

1º Click on the folder and expand (show) your files.

My question is: How to do this for "Imagem2.jpg" without creating another function? I want to keep the same function.

Note: I want the help in pure Javascript, do not cite Jquery, because I’m not studying it yet.

1 answer

2


In HTML you can only have 1 unique ID per page, ie several elements with the same ID is invalid HTML. To select multiple elements you can use classes. It is also possible to have a selector that checks whether an ID starts with a given string... but classes are more correct.

However in your case I believe you don’t need classes or ids, you can use the element that calls mostrar as a reference if you pass the this. So you know which element was clicked and you can search lis inside it. You’ll have to iterate, but the code would be similar. In that case you could do so:

<ul>
  <li onclick="mostrar(this)">
    PASTA - Fotos
    <ul>
      <li>Imagem1.jpg</li>
      <li>Imagem2.jpg </li>
    </ul>
  </li><br>
  <li> PASTA - BOLETOS
    <ul>
      <li id="boleto">boleto.pdf</li>
    </ul>
  </li>
</ul>


<script>
  function mostrar(el) {
    const lis = el.querySelectorAll('li');
    lis.forEach(li => {
      li.style.display = li.style.display === 'none' ? 'initial' :
        'none';
    });
  }
</script>

And another improvement would be, instead of hiding with Javascript you can do this with a CSS class.

.esconder li {
  display: none;
}
<ul>
  <li onclick="mostrar(this)">
    PASTA - Fotos
    <ul>
      <li>Imagem1.jpg</li>
      <li>Imagem2.jpg </li>
    </ul>
  </li><br>
  <li> PASTA - BOLETOS
    <ul>
      <li>boleto.pdf</li>
    </ul>
  </li>
</ul>


<script>
  function mostrar(el) {
    el.classList.toggle('esconder');
  }
</script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.