5

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);

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

Comments

4

Look here

http://api.jquery.com/category/plugins/templates/

and an overview

http://www.borismoore.com/2010/10/jquery-templates-is-now-official-jquery.html

4 Comments

Extremely interesting. This is going to take me a bit of time to investigate, but I can see how powerful this could be!
I'm trying to understand how this works... is it possible to have templates within templates?
I believe it is possible to nest templates yes. Check out this presentation for more info slideshare.net/garann/…
I think jquery templates were removed.
1

I'm would use a templating system like iCanHaz.js

Comments

0

Append Child
Create Element
or most simply, innerHTML: http://www.tizag.com/javascriptT/javascript-innerHTML.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.