I am kind of new with front end development, and one problem I often have is not to repeat myself when generating HTML on the fly with JS/JQuery.
Let's consider a DOM object that has several states. Often, all you want to do with JS is to switch from one state to another. But doing this by calling html() on the DOM object makes you write the same HTML code at several different places (and in JS documents). So what's the DRY way of doing this?
Basically, what I would like to do instead, is pre-write in my HTML document a sample DOM for each state (without altering the document structure), and just be able to replace my DOM with the sample for the state I want on the fly.
var state1= $(HTMLRootElement).detach(); $(document.body).append(state2);
As long as you don't lose your reference to the state1 variable (otherwise it will be garbage collected) you can just later do this:
var state2= $(HTMLRootElement).detach(); $(document.body).append(state1);
This way the HTML elements still exists in memory, they are just not present on the DOM tree.
Another way is to simply .hide() and .show() the content in question. Using .detach() you can choose to append the element of the state you want in another place of your webpage, instead of having it fixed (like inside another div).