jQuery to construct elements I'm new to jQuery, and am using it to dynamically construct chunks of a page.

The created HTML is what I want, but I'm not sure if the way I'm generating it is sensible or idiomatic.

function setupIndex()
{
  $(document.body).append($("&lt;img/&gt;", {src : 'logo.png'}));
  var div = $("&lt;div/&gt;", {"class" : "content"}).appendTo(document.body);

  div.append("&lt;h2/&gt;", { text :'My Panels'});
  div.append($("&lt;table/&gt;", {id : 'maintable'}));
}

function addPanel(name, desc)
{
  if (!$("#maintable"))
    setupIndex();

  var row = $("&lt;tr/&gt;",{"class":"panels"}).appendTo("#maintable");

  var div = $("&lt;td/&gt;").appendTo(row);
  div.append($("&lt;h3/&gt;").append($("&lt;a/&gt;", { text : name, href : name + "/index.html"})));
  div.append(document.createTextNode(desc));

  div = $("&lt;td/&gt;").appendTo(row);

  var anc = div.append($("&lt;a/&gt;", {href: name + "/index.html"}));
  anc.append($("&lt;img/&gt;", { css : {width : "200px", height : "auto"}, src : name + "/thumbnail.png"}));
}
I know that the following might seem crazy at first but humour me for a minute.  The main improvement is so that variables are not reused (which confuses their meaning) and the subtle .appendTo("#maintable") is at the end (which means the document is altered once).

There is not functional need to store the objects into variables as they aren't re-used. I often try to write in this pattern as it looks more like the way you'd write html. 

if (!$("#maintable"))
    setupIndex();

$("&lt;tr/&gt;", {"class":"panels"})
    .append(
        $("&lt;td/&gt;")
            .text(desc)
            .prepend(
                $("&lt;h3/&gt;")
                    .append($("&lt;a/&gt;", { text : name, href : name + "/index.html"})))
            )
    )
    .append(
        $("&lt;td/&gt;")
            .append($("&lt;a/&gt;", {href: name + "/index.html"}))
            .append($("&lt;img/&gt;", { css : {width : "200px", height : "auto"}, src : name + "/thumbnail.png"}))
    )
    .appendTo("#maintable");