Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: generating html

Tags:

html

jquery

Is there a better way to do the following?

var html;
var i;
for (i=0; i < 4; i++) {
    html += '<div class="row">';
    html += '<span class="label">Dining Style:</span>';
    html += '<span class="control">';

    var j;
    for (j=0; j < 3; j++){
        html += '<div class="attribBox">';
            html += '<ul>';
                html += '<li><input type="checkbox" /> item 1</li>';
            html += '</ul>';
        html += '</div>';
    }
    html += '</span>';
    html += '<div class="clear"></div>';
}

$("#content").html(html);
like image 454
dcolumbus Avatar asked Oct 21 '10 21:10

dcolumbus


1 Answers

Instead of creating the html, you can use jquery functions, available in 1.4+, to make you code much cleaner. Here is an example:

$("#content").append($("<div/>", {class : 'row'}).append($("<span/>", {class:'label', text : 'Dining Style'})))

The above code will generate:

<div class="row"><span class="label">Dining Style</span></div>

You still have to loop to create the three children but this is much cleaner.

like image 62
Amir Raminfar Avatar answered Oct 06 '22 10:10

Amir Raminfar