Winthan Aung
Winthan Aung

Reputation: 351

JavaScript DOM coding - 'undefined' error

I am having problem with this error:

'undefined' is null or not an object'

Can you please have a look and let me know. In my coding, I want to have simple DOM JavaScript code

<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<script>
    init();
    function init()
    {
        getElementByTabIndex("4", "submit")[0].addEventListener("click", Verify, false);
    }
    function Verify() {
        alert('done');  
        // all verification code will be here...
    }
    function getElementByTabIndex(index, type, node)
    {
        if (!node)
        { 
            node = document.getElementsByTagName('body')[0]; 
        } 

        var a = [];
        els = node.getElementsByTagName('*'); 
        for (var i = 0, j = els.length; i < j; i++) 
        { 
            if (els[i].tabIndex == index && els[i].type == type)
            { 
                a.push(els[i]);
            } 
        } 
    return a; 
}

</script>
<body>
<input type="email" id="email" /><input type="password" id="pass" /> <label class="Login" for="login"><input value="Log In" tabindex="4" type="submit" id="login"></label>
</body>
</html>

Upvotes: 0

Views: 5933

Answers (3)

mhe
mhe

Reputation: 703

'body' isn't available to javascript at the time you are trying to call init().

call your init method when the dom has finished loading, like so:

window.onload = function (){
    init();
}

note that in order to make this work across browsers (if you plan on using it outside your planned Safari extention) you will have to do some extra work. more info: http://www.javascriptkit.com/dhtmltutors/domready.shtml

Upvotes: 0

Praveen Prasad
Praveen Prasad

Reputation: 32137

You have to move you code at bottom or call init() after body is loaded.

Reason: you are trying to get elements even before they exists.

Eg :

<head>
   <script>
      var elm= document.getElementById('id');

      //this will be always undefied, as trying to read element even before they exist
   </script>
</head>

<body>
  <div id='foo'></div>

   <script>
      var elm= document.getElementById('id');

      //this wont be undefined 
   </script>

</body>

Upvotes: 3

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385405

You call:

if (!node) { 
    node = document.getElementsByTagName('body')[0]; 
} 

But your script runs before the DOM has finished loading, and so the body tag does not exist.

So node is undefined, and when you attempt the following, you get your error:

node.getElementsByTagName('*');

Run init() on document load, instead of immediately.


PS. jsfiddle and Firebug allowed me to debug this very quickly.

Upvotes: 0

Related Questions