Question about loops

as you can see there are codes of two different loops.
my question is how come the do while loop ran without problems while the for loop didn’t.
had to use load event to force run it.

what’s btns? how it is obtained?

added it to the code.
those are bttons, iam tryed to listen on.

if it runs before the page had time to load, then you find yourself with btns not having the value you want

the other loop doesn’t deal with html elements so there is not this issue

wait what?
the way i set it up with force runing it, made it work just fine.
i get now all the correct values of each btn everytime.

without that it didnt run at all, i put console.log(“true”)
it didnt log.
so… iam asking howcome one loop ran just fine on its own and the other didnt at all until i forced it to run.

where did you put this?

inside the loop ofc, the for loop.
that how i know it didnt run.
there was nothing on the console window or however its called.

now it all works good, iam just curious why, thats all.

if you don’t share your whole code it’s difficult o say

but, if this let btns= document.getElementsByTagName('button'); run before the page could load, the buttons not exist yet, and btns.length is 0, so the loop doesn’t run

but I have actually no idea, as it is impossible to say these things without seeing the whole code put together

1 Like

hmmm… thats interesting theory.
might be the case, how can i prevent it from happening?

i dont mind sharing the code : D.
its nothing advanced tho, iam beginner.
it was home work assignment.

make sure your code executes only after the page has loaded, the way you did is one such way, there are a few others which yiou can find if you google a bit.

Also, to verify, you can add just above the loop in the code you had before console.log(btns) and see what appear in the console

1 Like

think i checked and they were all there.
but! cant say it for sure.
anyways, thanks man.

seem like you are right, before the run method it says htm collection length 0.
than when i placed it in the run method it says length 20.

are there other ways to deal with this situation?

also i wouldnt mine feedback on my code.

little side note, is that the do...while loop runs the code first before it checks the condition.