The only thing i want to do is I click a button, than the text within button change, actually i done this:
<button id='todo-button' onclick='changeToDone()'>To Do</button>
<script>
function changeToDone() {
let toDone = document.getElementById('todo-button');
toDone.innerText = 'Done';
}
my question is I want to change the function like this:
function changeToDone() {
let toDone = document.getElementById('todo-button');
let text = toDone.innerText;
text = 'Done';
but it does not work.
I just start to study js, so I want to know Is there a way achieve my second code and how.
>Solution :
This will not work. To see why you can reason about the value of text
.
function changeToDone() {
let toDone = document.getElementById('todo-button');
let text = toDone.innerText;
text = 'Done';
In line 3, text is set to toDone.innerText
. toDone.innerText
GETS (returns) a string value. text
now holds this string value, not a reference to innerText. text
is the string currently in innerText, not the innerText itself.
Now in line 4, text
just gets assigned the value of the string 'done'
. There is no reference to innerText so nothing can change there.
To actually set the inner text you have to use the setter side of toDone.innerText
. Thus toDone.innerText = 'Done';
is imperative.