Alex Rivera | Logout

Building HTML (~= DOM) using jQuery

Asked 2009-04-30T02:39:28.413
18

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("<td>").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"

Edit
Report

1 Answer

14

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");
answered 2009-04-30T02:45:42.627

Your Answer