最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript document.getElementById not working - Stack Overflow

programmeradmin2浏览0评论

Following is my javascript program. I am trying to get all child tags of parent div tag but when I am running the program document.getElementById('abc') returning null.

function init(){
//               currentDiv = document.getElementById("intro");
                alert("working");
                count = 0;
                divs = document.getElementById('abc').getElementsByTagName("div");

                alert("HI " + divs)
                currentDiv = divs[count];
                nextDiv = divs[count + 1]
                count = count + 1;
            }

window.onload = init();

Following is my div tag definitions:

<div id='abc'> 
<div></div>
</div>

thanks.

Following is my javascript program. I am trying to get all child tags of parent div tag but when I am running the program document.getElementById('abc') returning null.

function init(){
//               currentDiv = document.getElementById("intro");
                alert("working");
                count = 0;
                divs = document.getElementById('abc').getElementsByTagName("div");

                alert("HI " + divs)
                currentDiv = divs[count];
                nextDiv = divs[count + 1]
                count = count + 1;
            }

window.onload = init();

Following is my div tag definitions:

<div id='abc'> 
<div></div>
</div>

thanks.

Share Improve this question edited Mar 8, 2011 at 15:19 Lightness Races in Orbit 386k77 gold badges666 silver badges1.1k bronze badges asked Mar 8, 2011 at 15:04 SandySandy 14.1k22 gold badges79 silver badges111 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 9

The problem is in this line:

window.onload = init();

You are running init and setting the return value as the value of window.onload. My guess is that the code is being executed before the DOM is ready, i.e. before the divs exist.

Try this instead:

window.onload = init;

I suggest you start using jQuery instead, then you have much more powerful tools for this kind of DOM search/traversing

<body onload="init()">
    <div id='abc'> 
        <div></div>
    </div>
</body>

this probably solves your problem

发布评论

评论列表(0)

  1. 暂无评论