javascript document.getElementById not working - Stack Overflow

Following is my javascript program. I am trying to get all childtags of parent div tag but when I am

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

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

相关推荐

  • javascript document.getElementById not working - Stack Overflow

    Following is my javascript program. I am trying to get all childtags of parent div tag but when I am

    1天前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

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

关注微信