-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
  • 1,892
  • 3
  • 26
  • 46

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
  • 259,174
  • 73
  • 529
  • 557
  • 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