Replace HTML on the fly with Javascript/JQuery, the DRY way

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

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

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).

Need Your Help

Hibernate Criteria that compares only 'Minute' component of Date data type

java hibernate

I have written a Hibernate criteria to filter and display records that have a certain Time input.

Displaying a button link in “do not show images” mobile mode

html button mobile hyperlink imageview

I have a page on a third-party site. On the page a have a linked button and it works perfectly on PC, but while I am browsing my page on my Iphone I got a mobile version of the third-party site for...