javascriptforeachinnerhtmlgetelementbyid

Why do I only get the last digit when looping through an array using getElementById().innerHTML


<div id="demo"></div><br>
<script>
    let a = [1,2,3];
    a.forEach(function(item){
    document.getElementById('demo').innerHTML=item;
    })
</script>

From the above code I can only get the last digit. Why it is not showing all digits in the array? When I use innerHTML+=item, it is working fine.

What is the difference between = and += here? I found that every tutorial explaining that += means x = x + y. But I believe there is a huge logic behind the scenes of +=.


Solution

  • = and += are not the same

    document.getElementById('demo').innerHTML=item;
    

    will set to a single item each time in the loop. So going through three times your would be setting the innerHTML like this:

    will append the item and is the same as

    document.getElementById('demo').innerHTML=document.getElementById('demo').innerHTML + item;
    

    So each time through you will be executing: