function CheckavailOnload()
{
var elems = document.getElementsByClassName('box-collateral box-related');
for(var i = 0; i < elems.length; i++){
if(elems.style.visibility == 'visible')
{
var av = document.getElementsByClassName('availability in-stock');
for(var i = 0; i < elems.length; i++) {
av[i].style.visibility = 'visible';
}
}
else
{
var av = document.getElementsByClassName('availability in-stock');
for(var i = 0; i < elems.length; i++) {
av[i].style.visibility = 'hidden';
}
}
}
}
CheckavailOnload();
here i am trying to check the visibility of div “box-collateral box-related” if it is visible i want to toggel the visibility of another paragraph with class name “availability in-stock”
getElementsByClassName()always gives you a HTMLCollection object, even if it had only one member. HTMLCollection object doesn’t havestyleproperty, hence you need to iterateelemsin the firstifto check the visibility, just like you’ve done further in your code.If you’re sure there’s only one member, you can check it’s visibility by using
elems[0].style.visibility.If you want to check the visibility of a particular element, you can give it an
idand get that element usingdocument.getElementById().EDIT
Thanks for a fiddle, now we can have some results.
So, maybe you don’t need that
id, the actual problem occurs when trying to getstyle, if it’s not explicitely assigned. To tackle this, you need to usegetComputedStyle():This code will check all elements assigned to classes
box-collateral box-related. A working demo at jsFiddle.Notice also use of
window.onload, which makes sure, that you’re not trying to get elements before they are parsed. I switchedelemstoavinfor...j– andfor...k-loops, supposed to work correctly, if there were different number of elements inelemsandav.If the first found element with maintioned classes is the one to check, you can simply replace
iwith0in allelems[i]expressions.If you want to check only a particular element, you can give it an
id, and get a reference to it withgetElementById(). In HTML:And then in the script: