2

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.

0

2 Answers 2

4

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

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

1 Comment

How do I append multiple elements then?
0

Use templates like Handlebars or EJS to decouple templates from the behavior specific code. Handlebars have an extra added feature, that is to precompile the template and convert it in a minified js. This minified js actually reduces the http calls and loads the page faster.

While in the template, you can add classes or ids to give styling mentioned in common css files.

1 Comment

Did you miss the bit where the OP asked not to be directed to templating libs? :)

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.