开发者

DOM GetElementsByTagName Problem

开发者 https://www.devze.com 2023-04-07 04:23 出处:网络
I am just starting out learning JavaScript and I have just reach the DOM section of my course. I have a page with 10tags on it and I have created the following JavaScript to tell me how many I have.

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.

Th开发者_Go百科anks


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>


Put the script at the end of your document (before you close </body>):

0

精彩评论

暂无评论...
验证码 换一张
取 消