简体   繁体   中英

How can I select all elements with the same class name?

I have a Boolean variable. It is stored in a hidden input field. Basically, if the user is signed in, it is false , if not, it is true .

There are download buttons which will link to a file download. My aim is to make it so that, if they aren't signed in, the button will not show, and the link will not work (it would be nice to have an alert saying they need to sign in or something, but that would probably be more effort than it's worth).

I have a function that performs onload of body:

function hide_download_btns(){
if (document.getElementById('download_btn_var_input').value == "true") {
    document.getElementsByClassName('project_download_btn').item(0).hidden = true
    }
}

My problem is where it asks for the nth term .item(0) . This is where it selects the div on which to perform the function, however, I want the function to affect all div s with the class name 'project_download_btn'.

I'm not a fan of jQuery, so it would be great to avoid that if possible.

You can simply loop through the elements instead of just taking the 0th.

var buttons = document.getElementsByClassName('project_download_btn');

for(var i=0; i< buttons.length; i++){
    buttons[i].hidden = true;
}

document.getElementsByClassName返回数组,所以你感兴趣的是:

document.getElementsByClassName('project_download_btn')[0]
if (document.getElementById('download_btn_var_input').value == "true") {
    var el = document.getElementsByClassName('project_download_btn');
    for (var i = 0; i < el.length; i++) {
        el[i].hidden = true;
    }
}

Loop through each div that contains your download button and set hidden to true :

if (document.getElementById('download_btn_var_input').value == "true") {
    var button_divs_array = document.getElementsByClassName('project_download_btn');
    for (var i = 0; i < button_divs_array.length; i++) {
        button_divs_array[i].hidden = true;
    }
}

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