Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New to the CF scene
    Join Date
    Oct 2008
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question DOM GetElementsByTagName Problem

    Hello,

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

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

    Code:
    <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

  • #2
    Senior Coder Logic Ali's Avatar
    Join Date
    Sep 2010
    Location
    London
    Posts
    1,028
    Thanks
    0
    Thanked 207 Times in 202 Posts
    In your view, when does that script run?

  • #3
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,458
    Thanks
    76
    Thanked 4,373 Times in 4,338 Posts
    What Logic Ali is pointing out:

    If you have that code in the <head> of your page, then that's the right answer.

    Only if you put that code *after* the last <a> on the page will it give you the answer you are looking for.

    Or only if you delay its execution until the page is loaded.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #4
    Regular Coder
    Join Date
    Sep 2011
    Location
    Sweden
    Posts
    154
    Thanks
    1
    Thanked 22 Times in 22 Posts
    In other words, this would work:
    Code:
    onload = function(){
      var myLinks = document.getElementsByTagName("a");
      console.log("We have ", myLinks.length ," many links on the page")
    };


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •