Though this is a very old question, I thought it would be nice to update it with recent information;
Since jQuery 1.8 there is a jQuery.parseHTML() function which is now a preferred way of creating elements. Also, there are some issues with parsing HTML via $('(html code goes here)')
, fo example official jQuery website mentions the following in one of their release notes:
Relaxed HTML parsing: You can once again have leading spaces or
newlines before tags in $(htmlString). We still strongly advise that
you use $.parseHTML() when parsing HTML obtained from external
sources, and may be making further changes to HTML parsing in the
future.
To relate to the actual question, provided example could be translated to:
this.$OuterDiv = $($.parseHTML('<div></div>'))
.hide()
.append($($.parseHTML('<table></table>'))
.attr({ cellSpacing : 0 })
.addClass("text")
)
;
which is unfortunately less convenient than using just $()
, but it gives you more control, for example you may choose to exclude script tags (it will leave inline scripts like onclick
though):
> $.parseHTML('<div onclick="a"></div><script></script>')
[<div onclick="a"></div>]
> $.parseHTML('<div onclick="a"></div><script></script>', document, true)
[<div onclick="a"></div>, <script></script>]
Also, here's a benchmark from the top answer adjusted to the new reality:
JSbin Link
jQuery 1.9.1
$.parseHTML: 88ms
$($.parseHTML): 240ms
<div></div>: 138ms
<div>: 143ms
createElement: 64ms
It looks like parseHTML
is much closer to createElement
than $()
, but all the boost is gone after wrapping the results in a new jQuery object