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.

Answers


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


Need Your Help

How to enable PDO on a server with very limited access?

php iis pdo iis-6 php-5.2

I want to run a website on a server (actually only part of the server) I have a very limited access to. The only two things I can do is to connect via FTP to my part in the server and to connect to...

regex for alphanumeric and allow an additional character also

javascript regex

How could I allow a string to match alphanumeric characters and a comma character

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.