0

Guys can someone pls explain me whats wrong with this code?

The code: var e=document.getElementsByClassName('uline'); for (var i=0;i<=e.length;i++){ e[i].style.backgroundColor="white"; } var lin=document.getElementsByTagName('a'); for(var a=0;a<=lin.length;a++){ lin[a].style.color='rgb(55, 106, 247)'; lin[a].style.borderColor='white'; } When running the code it stops from the first loop above ,but the first loop works and the second doesn't. In the chrome developer tool it says Uncaught TypeError: Cannot read properties of undefined (reading 'style') Can someone explain what had gone wrong?

3rd Jul 2022, 1:19 PM
KADHM
KADHM - avatar
5 Answers
+ 2
// Try it for (let i=0; i<e.length-1; i++){ ... }
3rd Jul 2022, 1:23 PM
SoloProg
SoloProg - avatar
+ 2
If you are sure there are elements within the document having "uline" class, and also the hyperlinks; then your problem was with the loop condition. You should set the loop to run while the counter variable was less than the array length, not while the counter was less than or equal to the array length This is because indices are zero-based positive values, from 0 up to (length of array - 1, inclusively ). So if you have a 20 elements array, valid indices begins with 0 (zero), and ends with (20 - 1 ~ 19) (Edited)
3rd Jul 2022, 1:54 PM
Ipang
+ 1
yes it worked .thank you @soloprog. And also can I know why its worked, if you don't mind.
3rd Jul 2022, 1:53 PM
KADHM
KADHM - avatar
+ 1
K.A.D.H.M he answered it :)
3rd Jul 2022, 2:02 PM
SoloProg
SoloProg - avatar
+ 1
@Ipang Thanks for your explanation.
3rd Jul 2022, 3:38 PM
KADHM
KADHM - avatar