How to select several elements whose ID contains a word

2

Hello with javascript I'm doing a function where I want to hide several elements, the problem is that if I use getElementById I can only select a single element, and I would like to hide several that have a similar ID; example, 'checkbox1', 'checkbox2'

Javascript function:

function activarcheck(){
        var check = document.getElementById("checkbox");
        if(check.style.display=== "none"){
            check.style.display="block";
        }else{
            check.style.display="none";
        }
    }

html:

<td>
   <div id="checkbox1"class="container oculto">
       <input type="checkbox" autocomplete="off" disabled>
   </div>
</td>
 <td>
    <div id="checkbox2" class="container oculto">
        <input type="checkbox" autocomplete="off">
   </div>
</td>
    
asked by Talked 27.04.2018 в 17:33
source

1 answer

3

Instead of selecting by id, you can select by class using gelElementsByClassName like this:

function activarcheck(){
    var checks = document.getElementsByClassName("oculto");
    for(var i=0; i<checks.length; i++) {
        if(checks[i].style.display=== "none"){
            checks[i].style.display="block";
        }else{
            checks[i].style.display="none";
        }
    }
}
<td>
   <div id="checkbox1"class="container oculto">
       <input type="checkbox" autocomplete="off" disabled>
   </div>
</td>
 <td>
    <div id="checkbox2" class="container oculto">
        <input type="checkbox" autocomplete="off">
   </div>
</td>
<input type="button" onclick="activarcheck();" value="Esconder"/>
    
answered by 27.04.2018 / 17:40
source