Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I set a variable in script equal to a value of button, than i change the variable to change this button's name

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading