Reputation: 2146
I want to store the display area of a page in a variable (display
in the code), i.e. the innerHTML of the display
div in my example, but when I do that I cannot modify its content at all.
function stored() {
var display = document.getElementById("display").innerHTML;
display = "Bonjour";
}
function notStored() {
document.getElementById("display").innerHTML = "Hello";
}
<button onclick="stored()">Stored in variable</button>
<button onclick="notStored()">Not stored in variable</button>
<div id="display"></div>
How should I do?
Thank you for your help.
Upvotes: 2
Views: 2433
Reputation: 2682
That's because you assigned a new value to your display
variable. What you want to do is to set the innerHTML
of display
to a variable, eg stored
. By doing that, you stored your desired innerHTML
as a variable.
function stored() {
var stored = "Bonjour";
var display = document.getElementById("display").innerHTML = stored;
}
function notStored() {
document.getElementById("display").innerHTML = "Hello";
}
<button onclick="stored()">Stored in variable</button>
<button onclick="notStored()">Not stored in variable</button>
<div id="display"></div>
Upvotes: 3
Reputation: 33726
The innerHTML attribute is a simple String, therefore it's immutable, moreover, you're only assigning a value to a variable rather than updating the current HTML content.
You need to assign the new value to the attribute innerHTML
:
function stored() {
document.getElementById("display").innerHTML = "Bonjour";
}
function notStored() {
document.getElementById("display").innerHTML = "Hello";
}
<button onclick="stored()">Stored in variable</button>
<button onclick="notStored()">Not stored in variable</button>
<div id="display"></div>
Upvotes: 2