Nirali Acharya Nirali Acharya - 3 months ago 13
HTML Question

Solved: Cannot get element id in javascript inside for loop

I am trying to use getElementById() inside loop as the id of my each div I want to get is in sequence like total_comments1, total_comments2, total_comments3,.. and so on. This ids are assigned by output using php.

Here is my code to display my div:

<?php
$i=0;
while( $row = mysqli_fetch_assoc($ret) ):
$i++;
?>
<tr>
<td class="col3 col">
<div id="<?php echo "total_comments".$i ?>"></div>
</td>
</tr>




Here is my javascript code:

<script>
for(var i in (result.response)) {
var a=document.getElementById("total_comments" + i );
a.innerHTML = result.response[i].posts;
}
</script>


When I use only "total_posts" in document.getElementBy ID it does not give any error. But when I use "total_posts"+i it gives error on next line. Cannot set property 'innerHTML' of null

Answer

Array have starting index from 0.

In your case, you are incrementing $i before assigning.

That is causing your ids start from 1 not 0

You should increment it after assigning.

Corrected code:

<?php
$i=0;
while ($row = mysqli_fetch_assoc($ret)):
?>
 <tr>
  <td class="col3 col">
   <div id="<?php echo "total_comments".$i ?>"></div>
  </td>
 </tr>
<?php
 $i++;
endwhile;
?>