-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 withdisplay: 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– Ricardo Pontual
Have as yes using foreach()
– hugocsl
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.
– Augusto Vasques