tags:

views:

1481

answers:

2

I may be doing something wrong, but I haven't been able to find a good way to build basic HTML/DOM structures, like lists, dynamically. Simple example would be building a table (table element, row, cells, with properly escaped text content) given input like json (objects).

The problem I have is that most calls (like ".append()", ".html()", ".text()") do not seem to chain in intuitive (to me, anyway) way. For example, you can't do something like:

$("#divId").append("<table>").append("<tr>").append("<b>").text("some text");

text() call seems to wipe out content at main level; and appends likewise add stuff within same scope. I would expect appennd() to return content being added, but it seems to be returning its own context.

I know there is simple "appendText()" extension that helps with last part. But how about others?

For what it's worth, right now I revert back to DOM, by something like

$("#divId")[0].appendChild(document.createElement("table"))....

but that's pretty verbose.

So I am hoping I am missing something totally obvious... but what? Call other than append()?

I tried browsing jQuery reference docs, googling, but most docs just use "embed all stuff in a string"; which has problems, including that of not quoting textual content properly.

(also: no, this is not a dup of "JQuery: Build HTML in ‘memory’ rather than DOM"

+3  A: 

You can do this:

$("#divId").append("<table>").append("<tr>").append("<b>").text("some text");

as either:

$("#divId").append("<table><tr><td><b>some test</b></td></tr></table>");

or

$("<b></b>").text("some text").appendTo("<td></td>").appendTo("<tr></tr>").appendTo("<table></table>").appendTo("#divId");
cletus
Latter would work -- former has the problem of text potentially having ampersand and less-thans. Second one sounds like it'd do the trick.I guess I didn't read docs for appendTo() well enough, somehow I thought it wouldn't work this way. Makes total sense if it does, given your sample. :)
StaxMan
on your third example you can go event shorter and do $('<b />').text('bolded text');
bendewey
Hmmh. Actually... because of order reversal (which I missed first) it gets bit tricky, when list entries are added in loop.But it should be possible still.
StaxMan
A: 

Quick note: additionally, AppendDOM plugin looks like it can also simplify the task.

StaxMan