tags:

views:

57

answers:

3

iam using jquery and want to do below written

    //this is a template
     <div class='main'>
    <div class='header'>Some Text</div>
    <div class='data'>
    // data goes here
    </div>
    </div>

// dom

 --------dom here-------------
<div id='red1' class='red'></div>
-----more dom (template is here)------------

what i want is, to bind template to any element(lets say id=red1) to have resulting dom as written below

//below is new dom

    --------dom here-------------
     <div class='main'>
    <div class='header'>Some Text</div>
    <div class='data'>
// element is wrapped with template
    <div id='red1' class='red'></div>
    </div>
    </div>
-----more dom (**template is still here**)------------
+1  A: 

jQuery doesn't have a built in templating mechanism, but there are a lot of JavaScript libs out there that provide it. mustache.js is one I like. Underscore.js, which is a good complement to jQuery, also has a simple template function.

noah
+1  A: 

It sounds like you could use the wrap function to wrap the template around divs with that id.

rosscj2533
+2  A: 

Something like:

// Capture the wrapper template html
var wrapper = $('<div class="main"><div class="header">Some Text</div><div class="data"></div></div>');

// Then replace the "red1" div with the wrapper and since the replaceWith 
// method returns the replaced element, you can just append it right back to your data div  
$('#red1').replaceWith(wrapper).appendTo(wrapper.find('.data'));
jjacka