Help - Search - Members - Calendar
Full Version: getElementsByClass() Seemingly Not Working Properly
HTMLHelp Forums > Programming > Client-side Scripting
703337
When I try to use a piece of code like this:

function HideAll() {
document.getElementsByClass("replay").style.display = "none";
}

It gives me an error saying that display isn't a valid option or something.
Here's a link to the site as well:

Click Here
Brian Chandler
I can only find getElementsByClassName, which returns an array of the matching elements. So you will need to loop through the array in order to set properties of each element...

https://developer.mozilla.org/en-US/docs/We...entsByClassName
703337
QUOTE(Brian Chandler @ Sep 21 2021, 01:26 AM) *

I can only find getElementsByClassName, which returns an array of the matching elements. So you will need to loop through the array in order to set properties of each element...

https://developer.mozilla.org/en-US/docs/We...entsByClassName


So something like this?

function HideAll() {
var replays = document.getElementsByClassName("replay");
replays.display = "none";
}

I've never used variables before so I'm not sure if that's right.
Christian J
The replays variable is an array (a list/collection) of all matches, so you must loop through them, and change the style of one at the time. Something like this FOR loop:

CODE
for(var i=0; i<replays.length; i++)
{
    replays[i].style.display='none';
}

(every time the loop is run, the value of i is increased by 1, for the whole length of the array).

If you know you only have a fixed small number of elements with the className "replay", you could skip the loop and instead do something like:

CODE
replays[0].style.display='none';
replays[1].style.display='none';
replays[2].style.display='none';

(the first item in an array has the index number 0).
Brian Chandler
I think it is neater (and safer) to use the JS "for-in" type loop. Roughly:

CODE

for(var p in replays)
  replays[p].style.display = 'none';


The counting style loop should work here, because the array has just been created, with indices from 0 to n-1, for an array of n items. But you have to be careful: if you change the array by removing some elements, it will no longer be numbered contiguously. But the for-in thing always goes through exactly all elements, so is less accident-prone.
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2024 Invision Power Services, Inc.