-3

First off I want to say I am quite new to JavaScript, but not entirely new to programming. I am familiar with python and just finished last semester at my college taking c++ and got an A. Now this semester I am taking JavaScript. I feel a bit silly asking this question because it seems quite stupid to me, but please be nice to me... Anyway, the very first part of my assignment is to write a function to count the hyperlinks on a webpage which the teacher provides. There should be 20. So, the teacher provides 2 lines of code to create an array of links and then console.log them. I copied and pasted them exactly as the teacher has them on the assignment page. The two lines are:

var myLinks = document.getElementsByTagName("a");
console.log("Links", myLinks.length);

Firstly, I typed these two lines directly into the console on chrome with the provided website open, the output is 20. Correct! So I happily copied and pasted the two lines into the linked JavaScript file and reload the page and it produces 0. I don't understand why... I hope this is not a silly question, but coming from c++ last semester, this really seems like a silly problem to me... Thank you for any help!

update: That was the whole JavaScript file. And I am only 3 weeks into the semester and still feel like this is all a bit over my head... Anyway, yes the script tag needed to be at the end of the body tag I guess. I did not realize it mattered... I apologize for the silly question... But thank you all, I appreciate the help.

Matt
  • 403
  • 1
  • 4
  • 6

5 Answers5

1
<script>
function getAnchorLinkCount() {
    var myLinks = document.getElementsByTagName("a");
    console.log("Links", myLinks.length);
}
</script>

then

<body onload="getAnchorLinkCount()">

You suppose to get count when your DOM entirely loaded

Jimish Gamit
  • 1,014
  • 5
  • 15
  • `body onload` is fired when a resource and its dependent resources have finished loading not `DOM` – Rayon Feb 08 '16 at 08:11
0

Most likely, the function executed before the html was completely loaded. To avoid such problems, always wrap your JS in a ready handler. With JQuery, use:

 $(document).ready(function(){
     // your code here
 });

For a pure JS equivalent, have a look at this thread.

Community
  • 1
  • 1
Derlin
  • 9,572
  • 2
  • 32
  • 53
0

The problem is, it's likely (we can't see all of your code) that the javascript is executing before DOM has finished loading.

Consider:

<script>
    var myLinks = document.getElementsByTagName("a");
    alert("Links" + myLinks.length);
</script>

<body>
    <a href = "foo"> foo</a>
    <a href = "bar"> bar</a>
</body>

Output: Links0

vs:

<body>
    <a href = "foo"> foo</a>
    <a href = "bar"> bar</a>
</body>

<script>
    var myLinks = document.getElementsByTagName("a");
    alert("Links" + myLinks.length);
</script>

Output: Links2

To avoid this issue there's a few suggestions:

  1. Put javascript code after the <body> tag, not in the head.
  2. Use something like jQuery's $(document).ready(...)
  3. Put the javascript in the head, but call the onload method in the body tag <body onload = "myInitFunction()">
dwjohnston
  • 11,163
  • 32
  • 99
  • 194
0

If you are dealing with DOM which is programming interface for HTML. You must wait for DOM structure to load so that it can be accessed in JavaScript

Use DOMContentLoaded, The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed.

Another solution could be including your script right before closing body tag which will be executed when all the DOM is loaded and parsed.

Try this:

document.addEventListener("DOMContentLoaded", function(event) {
  var myLinks = document.getElementsByTagName("a");
  console.log("Links", myLinks.length);
});

Note: As per the docs, A very different event - load - should be used only to detect a fully-loaded page. It is an incredibly popular mistake to use load where DOMContentLoaded would be much more appropriate, so be cautious.

Rayon
  • 36,219
  • 4
  • 49
  • 76
0

There is no problem with the code that you have written but the problem can be when you are executing it.

First you need to wait until DOM is ready then you can call the js methods. That is why it is document.... which mean from the DOM tree get my element.

There can multiple ways to execute once DOM is ready

  1. window.load
  2. DOMContentLoaded
  3. Put your script just before closing body tag. This ensure that your entire DOM is ready.
  4. If your are using jquery you can use $(document).ready(function(){})

Below is a snippet where the all js codes are at the bottom of the page.

<body>
<a href="#"> Link 1</a>
   <a href="#"> Link 2</a>
   <a href="#"> Link 3</a>
   <a href="#"> Link 4</a>
   <a href="#"> Link 5</a>
   <a href="#"> Link 6</a>
<script>
     // Will give a Collection of a tags
   var getListTagName = document.getElementsByTagName('a');
    console.log('document.getElementsByTagName ',getListTagName.length);

   // Does same but but document.querySelectorAll is preferred to match a css selector
   var getListQuery = document.querySelectorAll('a');
   console.log('document.querySelectorAll ',getList.length)
</script>
</body>

Hope this post will be helpful for you.

brk
  • 48,835
  • 10
  • 56
  • 78