Is there a better way to attach big to ul?

I have an li that has numerous nested divs. I am adding to ul like this:

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

      

the li structure is the same as the other lis in the ul, but I need to modify some elements.

My question is - am I just doing it wrong by manually writing out the whole structure?

+2


source to share


2 answers


Please do it,

provide a class / id for the li you want to add

Let's say you want to add

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

      



then

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

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

      

return if you have any problems i think it works

+1


source


If the template follows (standard HTML with periods for accepting variables), you can have a function build(data)

that takes your dataset and generates an html string. In the long run, it would be much more maintenance-friendly, also reusable.

Resig has its own boilerplate:

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



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

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!

+3


source







All Articles