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

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"?

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

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