Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"getElementsByTagName(...)[0]" is undefined?

I have the following code, which basically toggles through a bunch of images.

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">
            var num = 1;
            img = document.getElementsByTagName("img")[0];
            hbutton = document.getElementsByTagName("h1")[0];
            hbutton.onclick = function() {
                num += 1;
                img.src = num + ".jpg";
            }
        </script>
    </head>
    <body>
        <h1>Press Here!</h1>
        <img src = "1.jpg"></img>
    </body>
</html>

For some reason, when I run it, nothing happens, because of the following error as displayed by my Firebug console.

    hbutton is undefined    
---
    hbutton.onclick = function() {

When I run just the JS after the page has loaded however, it works perfectly fine!!! Why is this?

like image 639
Bobby Tables Avatar asked May 29 '12 21:05

Bobby Tables


People also ask

What is getelementsbytagname() function in JavaScript?

The JavaScript getElementsByTagName () function is used to return all elements of the given tag name in order they are present in the document. The getElementsByTagName () function is built in function in JavaScript. This is a function of DOM element or document object, so it is called as document.getElementsByTagName ().

Why it cannot find document getelementsbytagname (IMG)?

It cannot find document.getElementsByTagName ("img") when the Document isnt ready yet, because it is simply not there yet.

How to use getelementsbytagname (H1)?

Therefore, when it asks for getElementsByTagName ('h1'), there aren't any matching elements at that moment in time. You need to either: * move the code to the end of the script. * or wrap it in a function, and trigger the function to execute when the page has finished loading -- ie use the onload method.

How to return all the HTML tag elements in a specified element?

To return all the html tag elements in a specified elements, like to return a collection of all tags in the Div object as: The getElementsByTagName () function is a built in function in JavaScript which is used to return all elements by the given tag name in order of they are present in the document.


1 Answers

Your code is executing before the h1 tag is defined. You must run it in an onload handler or put it just before /body

like image 152
Julian Avatar answered Oct 05 '22 22:10

Julian