jQuery document.createElement equivalent?
Solution 1
Here's your example in the "one" line.
this.$OuterDiv = $('<div></div>')
.hide()
.append($('<table></table>')
.attr({ cellSpacing : 0 })
.addClass("text")
)
;
Update: I thought I'd update this post since it still gets quite a bit of traffic. In the comments below there's some discussion about $("<div>")
vs $("<div></div>")
vs $(document.createElement('div'))
as a way of creating new elements, and which is "best".
I put together a small benchmark, and here are roughly the results of repeating the above options 100,000 times:
jQuery 1.4, 1.5, 1.6
Chrome 11 Firefox 4 IE9
<div> 440ms 640ms 460ms
<div></div> 420ms 650ms 480ms
createElement 100ms 180ms 300ms
jQuery 1.3
Chrome 11
<div> 770ms
<div></div> 3800ms
createElement 100ms
jQuery 1.2
Chrome 11
<div> 3500ms
<div></div> 3500ms
createElement 100ms
I think it's no big surprise, but document.createElement
is the fastest method. Of course, before you go off and start refactoring your entire codebase, remember that the differences we're talking about here (in all but the archaic versions of jQuery) equate to about an extra 3 milliseconds per thousand elements.
Update 2
Updated for jQuery 1.7.2 and put the benchmark on JSBen.ch
which is probably a bit more scientific than my primitive benchmarks, plus it can be crowdsourced now!
Solution 2
Simply supplying the HTML of elements you want to add to a jQuery constructor $()
will return a jQuery object from newly built HTML, suitable for being appended into the DOM using jQuery's append()
method.
For example:
var t = $("<table cellspacing='0' class='text'></table>");
$.append(t);
You could then populate this table programmatically, if you wished.
This gives you the ability to specify any arbitrary HTML you like, including class names or other attributes, which you might find more concise than using createElement
and then setting attributes like cellSpacing
and className
via JS.
Solution 3
Creating new DOM elements is a core feature of the jQuery()
method, see:
- http://api.jquery.com/jQuery/#creating-new-elements
- and particulary http://api.jquery.com/jQuery/#example-1-1
Solution 4
I'm doing like that:
$('<div/>',{
text: 'Div text',
class: 'className'
}).appendTo('#parentDiv');
Solution 5
since jQuery1.8
, using $.parseHTML()
to create elements is a better choice.
there are two benefits:
1.if you use the old way, which may be something like $(string)
, jQuery will examine the string to make sure you want to select a html tag or create a new element. By using $.parseHTML()
, you tell jQuery that you want to create a new element explicitly, so the performance may be a little better.
2.much more important thing is that you may suffer from cross site attack (more info) if you use the old way. if you have something like:
var userInput = window.prompt("please enter selector");
$(userInput).hide();
a bad guy can input <script src="xss-attach.js"></script>
to tease you. fortunately, $.parseHTML()
avoid this embarrassment for you:
var a = $('<div>')
// a is [<div></div>]
var b = $.parseHTML('<div>')
// b is [<div></div>]
$('<script src="xss-attach.js"></script>')
// jQuery returns [<script src="xss-attach.js"></script>]
$.parseHTML('<script src="xss-attach.js"></script>')
// jQuery returns []
However, please notice that a
is a jQuery object while b
is a html element:
a.html('123')
// [<div>123</div>]
b.html('123')
// TypeError: Object [object HTMLDivElement] has no method 'html'
$(b).html('123')
// [<div>123</div>]
Rob Stevenson-Leggett
I love to code and snowboard. Follow me on twitter: @rsleggett
Updated on September 26, 2020Comments
-
Rob Stevenson-Leggett over 3 years
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.display = "none"; this.OuterDiv = odv; var t = d.createElement("table"); t.cellSpacing = 0; t.className = "text"; odv.appendChild(t);
I would like to know if there is a better way to do this using jQuery. I've been experimenting with:
var odv = $.create("div"); $.append(odv); // And many more
But I'm not sure if this is any better.
-
EscapeNetscape over 7 yearsjsben.ch/#/ARUtz - a benchmark for jquery vs createElement
-
T.Todua over 6 yearsPossible duplicate of Creating a div element in jQuery
-
Tyguy7 over 5 yearsUncaught TypeError: $.create is not a function
-
-
Vincent Robert about 15 yearsYou should get up to date. jQuery does not use innerHtml but parses the HTML string and internally builds a DOM tree using document.createElement(). This is core jQuery.
-
ruffin about 7 years"Better choice" to "create [any] element" might be strong. @siergiej's answer does a good job of saying
parseHTML
is good for html coming from external sources, but that "all the boost is gone after wrapping the results in a new jQuery object". That is, if you want to hard-code the creation of a new jQuery-wrapped html element,$("<div>stuff</div>")
style still seems to win. -
Guillermo Gonzalez almost 3 yearsWhy is this one so low on the answers? This is the one I fancy the most!
-
Master DJon almost 2 yearsAlthough it may be less primitive,
JSBen.ch
doesn't show any time, which I would expect in a benchmark. Am I wrong?