Search code examples
javascriptgetelementsbytagname

Cannot access getElementsByTagName from external js


This thing is driving me mad... I have a simple js script wich checks for all the links tag () in a page and check if two of those links at least correspond to a given href attribute. If I put the script in the main page as an inline script it works great. If I put it inside an external .js script on the same page, it doesn't find any element. Just like if it's only scanning its internal ones but not the parent document ones. the script is this

            var as,i,islink,l1,l2;
        l1 = false
        l2 = false
        as=document.getElementsByTagName('a');
        for(i=0;i<as.length;i++)
        {
            islink=as[i].href;
alert(islink);

            if(islink == 'http://www.linktocheck.com/')
            {
                if(!as[i].getAttribute('rel')) {l1 = true;}
            }
            if(islink == 'http://www.linktocheck.com/somedir/somepage.asp')
            {
                if(!as[i].getAttribute('rel')) {l2 = true;}
            }
        }
        if(!l1 || !l2) {alert('links not found in the page');}

I put alert(islink); for debug purposes to see if some link element has been found in the page or not. The HTML of the calling page is this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title>page a</title>
<meta name="robots" content="noarchive" />
<meta content="text/html; charset=iso-8859-1" http-equiv="content-type" /></head>
<body>
<script src="externaljstochecklinks.js?PARAMETER=somevalue" id="uniqueid" type="text/javascript"></script><div style="margin-top: 6px;margin-bottom: 4px;text-align: center;"><a href="http://www.linktocheck.com/somedir/somepage.asp" title="" target="_blank">[...]</a>&nbsp;&nbsp;&nbsp;<a href="http://www.linktocheck.com/" title="" target="_blank"><img src="http://www.linktocheck.com/skins/some/images/some.gif" alt="" style="border: none;vertical-align: middle;" /></a></div>

Why if I put the link check script inline it finds the elements if I put it as external it doesn't?


Solution

  • You have to wait for the DOM to finish loading before you can query it to find DOM elements.

    Your script appears to be at the beginning of the <body> section which means it will execute BEFORE the DOM has been parsed and loaded. Thus, there is nothing yet loaded to find.

    The simplest fix would be to move your <script> tag to the end of the body right before the </body> tag. You could also use an event listener and execute your code only when the event fires indicating that the DOM is ready.