Home > front end >  Can I set a variable in script equal to a value of button, than i change the variable to change this
Can I set a variable in script equal to a value of button, than i change the variable to change this

Time:06-22

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.

CodePudding user response:

Not really. In

let text = toDone.innerText;

Right when you reference .innerText, the element's value getter is invoked, and the value is returned. After that, reassigning the text variable to some other string won't do anything.

In order to change the text of an element like this, you need

(1) to invoke the .innerText setter

(2) with a this of the element whose text you want to change

So, in doing

toDone.innerText = 'Done';

all of those parts - the toDone (the this), the .innerText (the name of the property), and the = on its right side (so that the setter on that property gets invoked) - are essential parts of invoking the setter to change the text.

That said, it's possible to abstract it behind a function, or to save references to all of those necessary components behind a single identifier, eg.

const setText = text => toDone.innerText = text;

setText('Done');

But that's about as much as you can do, within reason.

CodePudding user response:

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.

  • Related