Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loop in javascript not working

i want to pick how many div are in my html. so i used .length method but it is not giving me desire result. you can see a demo in here http://jsfiddle.net/WbwuC/

<style>

.main { width:980px; margin:0 auto; border:solid 1px #F00; overflow:hidden}

.box { width:300px; float:left; margin-right:20px; background:#00F; height:200px;}
.new {border:solid 2px #333;}

</style>


<script type="text/javascript">


    var amy= document.getElementsByTagName('div');

    for (i=0;i<amy.length;i++){
        var jar= amy[i];
        }
     alert(jar)


</script>

</head>

<body>
<div id="main">
<div class="box"><h3>first</h3></div>
<div class="box"><h3>secnond</h3></div>
<div class="box"><h3>third</h3></div>

</div>

</body>
like image 640
Jitender Avatar asked May 07 '26 18:05

Jitender


2 Answers

This doesn't work because at the time that the script executes the document hasn't processed as for as the divs in the body. Try to move your script under the divs, or wait for the document loaded event.

like image 76
shanethehat Avatar answered May 10 '26 08:05

shanethehat


If your script runs while the page is loading, before the divs are present, there will be no divs yet. You should add a page load event to trigger the code. Your jsfiddle works btw... it has onload enabled for the code.

http://jsfiddle.net/EEjaP/

like image 23
Willem Avatar answered May 10 '26 08:05

Willem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!