jQuery pattern for DOM building (from strings)?

Noah Botimer botimer at umich.edu
Wed Sep 10 20:02:00 UTC 2008

Hi folks,

I can't think of a more qualified group to offer insight here.  When  
doing some modular DOM building, I hit an interesting jQuery thing.   
Specifically, I'm building up small chunks of DOM (from string) and  
returning them where they are being dropped in a larger chunk of DOM,  
etc.  I'm wondering if I'm what I'm doing is halfway clean, naive, or  

It's roughly like a decorator pattern.  What I'm running into is  
that, when I build up a given DOM chunk, it's at the top level in the  
jQuery object.  This forces me to make a decision between find() and  
filter() to attach events and so on.  It also makes append() / after 
() seem a little flaky.  So, I hacked it...

My simple hack around this has been to start with something like var  
dom = $('<div></div>'); and then doing append()s to that.  I can then  
do find() unconditionally, but I end up returning dom.children().   
Included p.s. is a contrived example of my technique, with respectful  
nods to Steve G.

Does anyone have any particular opinion about this?  Are the Fluid  
components handling this in some super elegant way?

Also, can someone advise about the warning about escaping slashes in  
strings going to DOM/jQuery objects: $('...markup...')? http:// 


$(document).ready(function() { $('body').append(buildPanel 
('awesome!')); });

function buildPanel(someParam) {
   var dom = $('<div></div>');
   dom.append('<div class="awesomePanel"></div>');
   var awesomeData = {};  //go get some awesome data based on someParam
   return dom.children();

function buildTitleBar() {
   var dom = $('<div></div>');
   dom.append('<div class="awesomeTitle"></div>');
   return dom.children();

function buildPanelBody(data) {
   var dom = $('<div></div>');
   //make a table of the awesome data
   dom.append('<table class="awesomeTable">...</table>');
   return dom.children();

More information about the fluid-work mailing list