Neerali Acharya
Neerali Acharya

Reputation: 623

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

Upvotes: 3

Views: 823

Answers (2)

jackomelly
jackomelly

Reputation: 543

The problem is on your php cycle, try to change it like this:

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

Upvotes: 2

Pupil
Pupil

Reputation: 23958

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;
?>

Upvotes: 5

Related Questions