Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
216,057 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
216,057 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.