javascript - Why does document.getElementsByName have a length of 0 despite having elements? -
this question has answer here:
the script runs before document
loaded, why console.log(b)
show elements in collection?
if console.log(b)
has elements why console.log(b[0])
show undefined
, console.log(b.length)
0
?
<html> <head> <script> function test(){ var b = document.getelementsbyname('a'); console.log(b); console.log(b[0]); console.log(b.length); } test(); </script> </head> <body> <form id="a" name="a"></form> </body> </html>
getelementsbyname
returns nodelist. it's object containing list of matching nodes, b
not null.
however, you're running script before dom ready, list of length 0 no first object. need delay script execution until after dom's been parsed, @ point form exist.
Comments
Post a Comment