rambodash
rambodash

Reputation: 87

Why does innerHTML inside a function get ignored when returning a value to innerHTML?

I am calling a function that prints to a div , then returns a string which is also printed to a div. The following will only print "two", but I was expecting it to print "one" then "two":

<body>
     <div id="view"></div>
</body>
<script>
global_cdiv = "view"
function test1(){
    document.getElementById(global_cdiv).innerHTML += "one" + "<br>";
    return "two";
}
document.getElementById(global_cdiv).innerHTML += test1();

</script>

No errors or anything show up in the debug. Why does Javascript ignore the innerHTML inside the function? (A work around would be to store the value from test1() into variable then printing it, but why can't test1 be used directly?)

Upvotes: 2

Views: 822

Answers (3)

thefourtheye
thefourtheye

Reputation: 239453

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>

Upvotes: 4

Ravi Teja
Ravi Teja

Reputation: 350

<body>
     <div id="view"></div>
</body>
<script>
global_cdiv = "view";
    var temp = ""; 
function test1(){
   temp = "one" + "<br>";
    return temp + "two";
}
document.getElementById(global_cdiv).innerHTML = test1();

</script>

Checkout the code above. This will solve your problem.

Upvotes: 0

Amine Hajyoussef
Amine Hajyoussef

Reputation: 4430

when you call document.getElementById(global_cdiv).innerHTML += test1() this is the order of execution:
1- evaluate document.getElementById(global_cdiv).innerHTML and save it into a temporary variable
2- execute test1 function
3- append the temporary variable to the return of test1 function
4- assign the result to document.getElementById(global_cdiv).innerHTML

so this is roughly what you're doing:

var temp = document.getElementById(global_cdiv).innerHTML
document.getElementById(global_cdiv).innerHTML = "one"  // inside your function
document.getElementById(global_cdiv).innerHTML = temp + "two" 

the second innerHTML (which is inside your function in your case) assignment get overwritten by the third one (not appended to "two")

Upvotes: 1

Related Questions