简体   繁体   中英

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM