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.
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>
):
精彩评论