w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Why does innerHTML inside a function get ignored when returning a value to innerHTML?
document.getElementById(global_cdiv).innerHTML += test1();

is a short form of

document.getElementById(global_cdiv).innerHTML =
document.getElementById(global_cdiv).innerHTML + test1();

Before evaluating test1() the innerHTML value is evaluated which is empty and that is getting concatenated with the result of test1() which is two. So, the actual expression becomes like this

document.getElementById(global_cdiv).innerHTML = "" + "two";

This overwrites whatever set inside test1(). Thats why you see only two.

To understand that it really overwrites it, change your test1() like this

function test1(){
    document.getElementById(global_cdiv).innerHTML += "one" + "<br>";
    console.log(document.getElementById(global_cdiv).innerHTML);
    return "two";
}

It will print one<br>





© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.