While working on some jQuery-based applications for TiddlyWeb (post upcoming), I noticed there was no obvious concise way to chain the creation of multiple nested elements.

Over the course of several discussions with Mike, we’ve come up with some simple idioms which we hope will make our code a little prettier:

var entries = ["foo", "bar", "baz"];

$("<ul />").
	append($.map(entries, function(item, i) {
		return $("<li />").text(item)[0];
	})).
	appendTo(container);
$.fn.create = function(html) {
	return this.append(html).children(":last");
};

$("<div />").
	create("<h2 />").addClass(className).text(heading).end().
	create("<p />").text(body).end().
	appendTo(container);

I’ve created a simple demo page (source) to better illustrate and explain this new approach, contrasting it with my previous code.

While I’m sure this sort of thing has been done before, it doesn’t seem to be common knowledge — at least nobody in the jQuery IRC channel had any ideas when I first asked.

Any comments (including YDICW, if necessary) would be appreciated.