I\'m refactoring some old JavaScript code and there\'s a lot of DOM manipulation going on.
var d = document;
var odv = d.createElement(\"div\");
odv.style.di
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(''))
.hide()
.append($($.parseHTML('
'))
.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('')
[]
> $.parseHTML('', document, true)
[, ]
Also, here's a benchmark from the top answer adjusted to the new reality:
JSbin Link
jQuery 1.9.1
$.parseHTML: 88ms $($.parseHTML): 240ms : 138ms: 143ms createElement: 64msIt looks like
parseHTML
is much closer tocreateElement
than$()
, but all the boost is gone after wrapping the results in a new jQuery object