I’m currently reading chapter 3 of Simply JavaScript learning how to find elements by tag name. When I insert the code
var listItems=document.getElementsByTagName(“li”);
var numItems=listItems.length;
alert(numItems);
I get 0. However, I have three <li> in my document.
When I run
var listItems=document.getElementsByTagName(“*”) ;
I get a length of 5 in my alert (<html>, <head>, <title>, <meta>, <script>, ). I tested for these tags individually (e.g. getElementsByTagName(“html”) and they are accounted for.
Why am I unable to target the body, ul, or list tags? I checked my document and it’s essentially the same as the book’s, except for the text between the elements.
you need to call the js to get the li elements after the document has finished loading and not before, or at least after the <li>'s have finished loading.
I’d be surprised if your book doesn’t mention somewhere in that example that elements must be loaded before you can access them using javascript. maybe it’s in the “fine print” somewhere
Haha it was mentioned at the end of Chapter 2. It talked about the problems which occur if your JavaScript runs before the HTML is done loading. It mentioned Core.start, but said further detail would be provided in later chapters. Therefore, I assumed all the code I ran wouldn’t have to worry about this issue -_-
Another solution instead of using Core.start is to move your script to the end of the body, just before the </body> tag. That way the rest of the body is available by the time the script does its thing.
However, for the sake of working in with the rest of the book, you should stick with using Core.start instead of other solutions.