...

View Full Version : DOM GetElementsByTagName Problem



Chudz
09-26-2011, 12:01 AM
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.



<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

Logic Ali
09-26-2011, 12:47 AM
In your view, when does that script run?

Old Pedant
09-26-2011, 01:23 AM
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.

ironboy
09-26-2011, 07:39 AM
In other words, this would work:

onload = function(){
var myLinks = document.getElementsByTagName("a");
console.log("We have ", myLinks.length ," many links on the page")
};



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum