3

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

7
  • 4
    can you check the generated html to see what is are id attribute values Commented Apr 20, 2016 at 10:19
  • 2
    also see the value of i in the loop Commented Apr 20, 2016 at 10:19
  • Yes, I have checked the id attribute values of div. They as I have mentioned above total_comments1, total_comments2,... Commented Apr 20, 2016 at 10:22
  • What is result.response Commented Apr 20, 2016 at 10:26
  • I did checked value of i by console.log() and it is like 0,1,2,3,.. Commented Apr 20, 2016 at 10:31

2 Answers 2

5

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;
?>
Sign up to request clarification or add additional context in comments.

6 Comments

You please read my php code again. I have initialized $i to 0 then at starting of loop I am incrementing it.
@NiraliAcharya, I have given you an approach to solve your question. It does not mean, it is perfect or you must follow it. It was just my observation. You can continue with your own code.
Sorry for that. But you see above I am incrementing variable i at loop starting.
@NiraliAcharya, as per my little knowledge, that is the issue. If you view source of your HTML, you can easily find it out.
This is my html output: <td class="col3 col"><div id="total_comments1"></td></div>
|
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.