简体   繁体   中英

How to get box index number using only javascript

i want to get box index number using Javascript. like i have four box so i want each box text have this appropriate number.

<head>

  <script type="text/javascript">
  function () {
   var Main= document.getElementById('container').getElementsByTagName('div');

for(i=0; i<Main.length;i++){



}

  }
  </script>
  <style>
  .box {
    float:left;
    margin-left:20px;
    position:relative
  }
  .width {
    position:absolute;
    left:0;
    top:0;
    color:#FFF;
    font-size:20px;
  }
  </style>
</head>
<body>
  <div id="container">
    <div class="box">

      <img src="img/sample1.jpg" height="200" width="300" />
    </div>
    <div class="box">

      <img src="img/sample2.jpg" height="200" width="350" />
    </div>
    <div class="box">

      <img src="img/sample3.jpg" height="200" width="150" />
    </div>
    <div class="box">

      <img src="img/sample4.jpg" height="200" width="100" />
    </div>
  </div>
</body>
window.onload=function() {
   var Main= document.getElementById('container').getElementsByTagName('div');

  for(var i=0; i<Main.length;i++){
    Main[i].innerHTML+= '<span class="title">box '+(i+1)+'</span>';
  }
}

DEMO

Replace all your JS with this below and place the script tag as the last tag in your body tag to assure the DOM is ready when this is called. You could also call this function from the onload event.

(function(){
    var Main= document.getElementById('container').getElementsByTagName('div');
    for(var i=0; i<Main.length;i++){
      Main[i].innerHTML += "box"+i;
    }
})();

http://jsfiddle.net/mmjW9/

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