javascript - document.getElementById is returning null - Stack Overflow

Here's the relevant HTML:<div id="navcontainer"><ul id="navlist">&

Here's the relevant HTML:

<div id="navcontainer">
    <ul id="navlist">
        <li><a href="#tab1">Item one</a></li>
        <li><a href="#tab2">Item two</a></li>
        <li><a href="#tab3">Item three</a></li>
        <li><a href="#tab4">Item four</a></li>
        <li><a href="#tab5">Item five</a></li>
    </ul>
</div>

The content of vertical.js

function tabber() {
    var li = document.getElementById("navcontainer");
    var as = document.getElementById('navlist');

    return;
}

window.onload = tabber();

When the tabber() function is executed, the function call to document.getElementById returns null. Why? The element navcontainer definitely exists. Any clues?

Here's the relevant HTML:

<div id="navcontainer">
    <ul id="navlist">
        <li><a href="#tab1">Item one</a></li>
        <li><a href="#tab2">Item two</a></li>
        <li><a href="#tab3">Item three</a></li>
        <li><a href="#tab4">Item four</a></li>
        <li><a href="#tab5">Item five</a></li>
    </ul>
</div>

The content of vertical.js

function tabber() {
    var li = document.getElementById("navcontainer");
    var as = document.getElementById('navlist');

    return;
}

window.onload = tabber();

When the tabber() function is executed, the function call to document.getElementById returns null. Why? The element navcontainer definitely exists. Any clues?

Share Improve this question edited Aug 15, 2013 at 17:48 allicarn 2,9192 gold badges29 silver badges47 bronze badges asked Jun 27, 2010 at 19:18 user377531user377531 233 bronze badges 1
  • are they both returning null, or just navcontainer? – user377136 Commented Jun 27, 2010 at 19:23
Add a ment  | 

3 Answers 3

Reset to default 12

Heh, the devil is in the detail. You are making a mistake while assigning the onload event.

window.onload = tabber();

will assign the result of tabber() to the onload property. Tabber() is executed straight away and not onload.

Change it to

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

that will work.

You're calling the tabber function incorrectly on window load.

Change it to

window.onload = tabber;

maybe the fact that you're using the JS keyword 'as' as a variable is the problem. remove that first.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743643658a4483388.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信