- Good, it turns out that I am doing some practices with
HTML
and the methoddocument.getElementsByTagName
does not work as I expect. This method is supposed to return aHTMLColletion
, which despite not being an array, is iterable as one, however when I try to iterate theHTMLCollection
return, it gives me unexpected results, let's see:
Code:
'use strict'; let body = document.getElementsByTagName('body'); // por qué no funciona como se espera el getElementByTagName console.log(body)
-This code returns what could be expected...
Result:
HTMLCollection { length: 0 }
However, if I try to iterate it the following happens...
Code:
'use strict'; let body = document.getElementsByTagName('body')[0];
console.log(body)
Result:
null
- On the other hand, if we iterate using the method
.item(0)
, instead of returningnull
returnsundefined
. On the other hand, on the console, everything works as I expect. What is this behavior due to?
You probably have your javascript code in your HTML code before the tag
body
:Browsers interpret HTML sequentially: in this case the Javascript is loaded, executed, and then the
body
:Solutions:
Add the code after the body.
Make the code run when the page finishes running:
src
), you can use the attributedefer
to indicate that the execution takes place after all the HTML is processed: