Home > Software design >  How can I change back the original value after modifying the text content in DOM with JavaScript
How can I change back the original value after modifying the text content in DOM with JavaScript

Time:01-04

Here's the original value,

<p >Log in</p>

Then I change it to "Welcome back, username" in DOM:

const labelWelcome = document.querySelector('.welcome')
labelWelcome.textContent = `Welcome back, ${username}`

But how can I change it back to "Log in"?

This seems to have completely changed the original value, and I can only change it back by modifying the text.

Is there a way to reset to the original value?

CodePudding user response:

Historic values won't be kept as you will overwrite the value of textContent. If you need access to the original value you need to store it somewhere in a variable (depending on your project) and then use that value to figure out what to update textContent with the second time.

One way of doing this is to write the value to a data attribute on the element, which can be accessed using the dataset property, something like:

labelWelcome.dataset.originalTextContent = element.textContent;
labelWelcome.textContent = "Welcome back";
labelWelcome.textContent = labelWelcome.dataset.originalTextContent;

CodePudding user response:

You can store the original value as a const and set when u need to.

const originalValue = 'Log in'
  • Related