-2

I noticed that when i try to get the new content from a div, the browser returns the old content of the div.

<div id="here">Old text</div>

<script>
document.getElementById('here').innerHTML = "New text";
</script>

Now the div text has changed:

 <div id="here">New text</div>

But when i try to alert the innerHTML of the div, i get the old text. Can you please tell me why, and how can i get the new text?

EDIT

Excuse me, i have provided a wrong javascript code. This is corect:

var text = document.getElementById('here').innerHTML;
document.getElementById('here').innerHTML = "New text";
alert(text); // returns "Old text"
Marian07
  • 2,303
  • 4
  • 27
  • 48
  • 2
    That shouldn't happen. Can you show how and in which order you set and get the text and show it? – GolezTrol Nov 23 '14 at 23:54
  • it's can't be. Show us a complete code – gdoron Nov 23 '14 at 23:54
  • 1
    It sounds like you probably assigned the old value to a variable, and are alerting the value of that *never-updated-since-then* variable. – Sampson Nov 24 '14 at 00:01
  • Change the order of the first and second rows. First change the innerHTML of 'here' and then define the text variable –  Nov 24 '14 at 00:04
  • possible duplicate of [Pass a string by reference in Javascript](http://stackoverflow.com/questions/1308624/pass-a-string-by-reference-in-javascript) – simonzack Nov 24 '14 at 00:05

1 Answers1

1

Note here that text is not a live reference to the innerHTML property of #here. It's a one-off assignment that won't be kept up to date on its own. You'll need to re-assign the new value, or alert the innerHTML property directly:

var text = document.getElementById('here').innerHTML;
document.getElementById('here').innerHTML = "New text";
alert(text);

Let's look at another approach:

var here = document.getElementById( "here" ); // This is a reference
here.innerHTML = "New Text";
alert( here.innerHTML ); // This will always be the actual contents

Hope this helps.

Sampson
  • 265,109
  • 74
  • 539
  • 565
  • Thank you! Is it possible to update the variable from my code? – Marian07 Nov 24 '14 at 00:14
  • 1
    @Marian07 Sure, you can keep it up to date too: `document.getElementById("here").innerHTML = text = "New Text";` Note the double-assignment. Regardless what approach you take, you should keep a reference to `#here` so you don't have to keep calling `getElementById`. – Sampson Nov 24 '14 at 00:15