Skip to content
Advertisement

Difference between console.log and document.getElementById()

const arr=[1,2,3,4,5];
arr.forEach(function(val){
console.log(val);
})
Output
1
2
3
4
5
const arr=[1,2,3,4,5];
arr.forEach(function(val){
document.getElementById("demo").innerHTML=val;
})
Output
5

My question is why I am getting different output even after using the same lines of codes.

Advertisement

Answer

in your code below:

const arr=[1,2,3,4,5];
arr.forEach(function(val){
document.getElementById("demo").innerHtml=val;
})

for each loop, it say html element with id demo set new innerHtml. So it will get value 1 and then overwrite by 2, 3, 4, 5. Finally, your final inner html would be 5. To show all arr value, you need to put to separate element look like this code:

const arr=[1,2,3,4,5];
arr.forEach(function(val){
document.getElementById("demo" + val).innerHtml=val; 
})
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement