getElementsByClass() Seemingly Not Working Properly, getElementsByClass("classname").style.display doesn't se |
getElementsByClass() Seemingly Not Working Properly, getElementsByClass("classname").style.display doesn't se |
703337 |
Sep 20 2021, 05:02 AM
Post
#1
|
Group: Members Posts: 2 Joined: 20-September 21 Member No.: 28,099 |
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 |
Sep 20 2021, 08:26 AM
Post
#2
|
Jocular coder Group: Members Posts: 2,483 Joined: 31-August 06 Member No.: 43 |
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 |
Sep 20 2021, 02:25 PM
Post
#3
|
Group: Members Posts: 2 Joined: 20-September 21 Member No.: 28,099 |
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 |
Sep 20 2021, 04:01 PM
Post
#4
|
. Group: WDG Moderators Posts: 9,760 Joined: 10-August 06 Member No.: 7 |
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 |
Sep 20 2021, 11:39 PM
Post
#5
|
Jocular coder Group: Members Posts: 2,483 Joined: 31-August 06 Member No.: 43 |
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. |
Lo-Fi Version | Time is now: 22nd January 2025 - 07:02 PM |