Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

How to save elements added to the DOM?

I know that in a program, you can create elements with javascript and add them to the DOM, that's easy. But I've noticed that when you run the program again, The element you added the first time you ran it is not there, and is replaced with the new element. This is likely because the interpreter checks all the physical HTML elements on the page, of which your added element is not one of. So I would like to know how to save an element in the DOM, and have it be there the next time the program runs, such as a newly added post in a forum. If this is possible, any help is appreciated

1 Answer

Steven Parker
Steven Parker
229,670 Points

If you wanted to make permanent changes to the HTML file, you'd need to send the info back to the server (sometimes called a "postback" operation), and the server program would need to receive that update and apply it to the HTML file directly.

In the browser, you could write it into the local storage, and each time the page is re-loaded your script could add it back to the DOM.

If your website supports a forum, you have other mechanisms where information in a database is used to construct pages on demand, and that process could be used for this as well.

Sorry, my own ignorance, but what is the local storage?

Steven Parker
Steven Parker
229,670 Points

That's a facility in the browser that allows you to save information from one session and read it back in another. There's a Using Local Storage with JavaScript workshop if you're interested.

Thanks Steven. Watched the video, looked a little more into JSON.stringify() and JSON.parse(), and I got my program to work exactly how I wanted it to.