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

Here’s the original value,

<p class="welcome">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?

>Solution :

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;

Leave a Reply