views:

57

answers:

1

As jQuery devs know, jQuery allows easy dynamic HTML creation like this

var d = $('<div/>')
    .append('some text')
    .append(
        $('<ul/>').append(
            $('<li/>').text('list item')
                      .css("color", "blue")
                      .click(function() {
                          // do something
                      })
        )
    );

What's a good coding convention for creating dynamic HTML like this that can go down an arbitrary number of levels, while still being able to identify where I am in the element hierarchy and can spot if I've closed all the parentheses/braces properly?

Please don't direct me to a templating library.

+4  A: 

Don't forget you can pass a map of properties as the second argument when creating a new element (jQuery 1.4 +):

$("<li/>", {
  text: "list item",
  css: { color: "blue" },
  click: function(){
    // do something
  }
)

See http://api.jquery.com/jQuery/#creating-new-elements

karim79
`css: { color: "blue" }` ;)
Nick Craver
Ah, thanks Nick - wasn't too sure about that one.
karim79
How do I append multiple elements then?
Jerome