简体   繁体   中英

Hide divs by class name instead of id in javascript

I have this JavaScript function that hides div tags from the condition if a checkbox is checked.

following is JavaScript Code:

function showMeA (div) {

var chboxs = document.getElementsByName("enableA");
var vis = "none";
for(var i=0;i<chboxs.length;i++) { 
    if(chboxs[i].checked){
     vis = "block";
        break;
    }
}
 document.getElementById(div).style.display = vis;
}

The problem is that function works based on the div's ID. I want to make it work based on the div's class name.

I have tried replacing the getElementById part with getElementsByClassName but, it doesn't work. Can someone propose an exact change that i need to implement in the function in order for it to work based on the div's class?

Thanks in advance.

而不是使用getElementById ,您可以使用getElementsByClassName

document.getElementsByClassName('className')

You can do this without any Javascript, just with pure CSS and some clever HTML structuring.

 .switchme { display: none; } #switch:checked ~ .switchme { display: block; } 
 <input type="checkbox" checked="checked" id="switch" /> <div class="switchme">Switch this div!</div> <div class="dontswitchme">This div won't be switched.</div> <ul class="switchme"> <li>This works without any JS.</li> <li>It is based on CSS 3's :checked pseudo selector.</li> </ul> <img class="switchme" src="http://placehold.it/300x200&text=SwitchMe" alt="" /> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM