简体   繁体   中英

javascript document.getElementById not working

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.

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, ie before the divs exist.

Try this instead:

window.onload = init;

我建议您改用jQuery ,然后再使用功能更强大的工具来进行此类DOM搜索/遍历

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

this probably solves your problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM