Reputation: 319
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.
Upvotes: 1
Views: 27441
Reputation: 1083
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;
}
}
Upvotes: 0
Reputation: 276
document.getElementsByClassName
returns array so what you are interested is :
document.getElementsByClassName('project_download_btn')[0]
Upvotes: 0
Reputation: 44740
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;
}
}
Upvotes: 0
Reputation: 78650
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;
}
Upvotes: 6