Search code examples
javascriptdomgetelementsbytagname

DOM GetElementsByTagName Problem


I am just starting out learning JavaScript and I have just reach the DOM section of my course.

I have a page with 10 tags on it and I have created the following JavaScript to tell me how many I have.

<script type="text/javascript">
var myLinks = document.getElementsByTagName("a");
console.log("We have ", myLinks.length ," many links on the page");
</script>

However in the console it reports this:

We have 0 many links on the page

This is not true as there are 10 links, 9 in the navgation section of the website and 1 in the footer.

If someone can tell me what I am doing wrong that would be great.

Thanks


Solution

  • You need to wrap this in an onload handler, because at the point of execution, the DOM isn't fully loaded:

    <script type="text/javascript">
      window.onload = function() {
        var myLinks = document.getElementsByTagName("a");
        console.log("We have ", myLinks.length ," many links on the page");
      };
    </script>