Search code examples
javascripthtmlfor-loopinnerhtmlconsole.log

document.write vs console.log vs innerHTML


javascript beginner here, i'm comparing these(document.write vs console.log vs innerHTML) to eachother and getting different result from innerHTML. As you can see 'document.write' and 'console.log' prints 'fname lname age', but innerHTML prints just ' age ', could somebody possibly explain this ?

var person = {fname:"John", lname:"Doe", age:25}; 
var x;
for (x in person) {
document.write(x+' ')

}
<p id="demo"></p>

console.log version :

var person = {fname:"John", lname:"Doe", age:25}; 
var x;
for (x in person) {
console.log(x+' ')

}

innerHTML version :

var person = {fname:"John", lname:"Doe", age:25}; 
var x;
for (x in person) {
document.getElementById("demo").innerHTML =x+' '

}
<p id="demo"></p>


Solution

  • When you use innerHTML you replace the text with the new one.

    If you want to display every value you need to use += operator which doesn't replace the string but it adds the current x value to the desired HTML Element.

    var person = {fname:"John", lname:"Doe", age:25}; 
    var x;
    for (x in person) {
      document.getElementById("demo").innerHTML += x+' '
    }
    <div id="demo"></div>

    Also, you could use different HTML Elements for each person value.

    var person = {fname:"John", lname:"Doe", age:25}; 
    let demoIndex = 1;
    for(let x in person) {
      document.getElementById("demo"+demoIndex).innerHTML =x+' '
      demoIndex++;
    }
    <div id="demo1"></div>
    <div id="demo2"></div>
    <div id="demo3"></div>

    I recommend the first option.

    More info about expressions and operators in JS here