Show/Hide Div

Asked

Viewed 84 times

-1

I’m having a hard time searching more than one div using Javascript I’d like to know if there’s a way to hide several div’s without having to copy the same JS code.

I made it HTML:

  <button id="modelos">Modelo 1</button>
  <div class="categoria">
    <li data-id="1">
      <span>Categoria 1</span>
    </li>
  </div>

  <button id="modelos2">modelo 2</button>
  <div class="categoria categoria2">
    <li data-id="2">
      <span>categoria 2</span>
    </li>
  </div>

CSS:

.categoria,
.categoria2 {
  display: none;
}

JS:

var btn = document.querySelector('#modelos');

var categoria = document.querySelector('.categoria');

btn.addEventListener('click', function(){
    
if(categoria.style.display === 'block'){
    categoria.style.display = 'none';
} else{
    categoria.style.display = 'block';
}
});

Then in case for me to hide and show the other div I had to copy the JS and paste again with a different name, I wonder if there is a more simplis way. has as?

  • no need to change using style.display, already has a class with display: none, just add/remove this class to change several elements, see this answer for an example: https://answall.com/questions/507244/evento-de-clique-no-js-mudar-a-div

  • Have as yes using foreach()

  • BEFORE ANSWERING THE QUESTION Take this example https://codepen.io/AugustoVasques/pen/mdWJxxZ , this is not the answer because it does not use javascript, but note that the user wants a button for each div and not a button for all Divs.

1 answer

-3

In pure javascript, you can create a function to facilitate and save codes.

Example:

function exibir(IDOBJETO,CLASSECSS){
var btn = document.querySelector(IDOBJETO);
var categoria = document.querySelector(CLASSECSS);
btn.addEventListener('click', function(){
    if(categoria.style.display === 'block'){
        categoria.style.display = 'none';
    } else{
        categoria.style.display = 'block';
    }
});

}

to call the function:

exibir('#modelos','.categoria')

To load the function automatically with the page load you can do by the Body tag for example

<body onload="exibir('#modelos','.categoria')">
  • User wants one button for each div. Not one button for all Divs.

Browser other questions tagged

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