views:

49

answers:

2

I have a li that has numerous nested divs. I am appending to a ul as follows:

     $("ul#List").append('<li><div>....many more nested divs...</li>');

the structure of the li is the same as the other lis in ul but i have to modify some elements.

My question is simply am I doing it wrong by manually writing out the entire structure?

+4  A: 

If it follows a template (standard HTML with spots to accept variables) you might have a build(data) function that takes in your dataset and builds an html string. It would be a lot more maintainable in the long run, also reusable.

Resig has his own templating shebang here:

http://ejohn.org/blog/javascript-micro-templating/

So your function (unrelated to the above link) might look like this:

var myObject = {
    name : "Alex",
    occupation : "Developer",
    faveFormat : "JSON"
}

function buildHTML(obj) {
    var name = obj.name;
    var occupation = obj.occupation;
    var faveFormat = obj.faveFormat;

    var resultHTML = [];

    resultHTML.push('<li><div>');
    resultHTML.push("My name is" + name);
    //etc etc
    resultHTML.push('</div></li>');
    var doneHTML = resultHTML.join(" ");
    return doneHTML;
}

Try it out!

Alex Mcp
+1  A: 

Please folllow this,

provide class/id to li which you want to append

suppose you want to append

<li id='templi'><div>......</div><li>

then

var lihtml = jQuery('#templi').clone();

jQuery("ul#List").append(lihtml);

revert if you have any problem, i think it works

Chirag