When you create an element by passing HTML to jQuery, there's a number of formats you could use, for example:
$("<span>").addClass("foo")
$("<span class=\"foo\"></span>")
etc...
Is there one style which works better than others?
When you create an element by passing HTML to jQuery, there's a number of formats you could use, for example:
$("<span>").addClass("foo")
$("<span class=\"foo\"></span>")
etc...
Is there one style which works better than others?
I previously thought there was no difference, but I was looking at the code which hks posted in this other question, and it showed some inconsistencies in IE. To investigate, I've put together a table.
Take a look at the results here: http://fisher.spadgos.com/stuff/jqueryConstructors.html
Basically it's things like this:
$('<a class="foo">').length; // in firefox, this == 1. IE, this == 0
$('<br></br>').length; // Firefox == 1; IE == 2
In IE it's very inconsistent, however in Firefox and Chrome all forms work pretty well.
The only methods which were consistent across all browsers were these:
$("<foo />") $("<foo>")
From the manual:
Create DOM elements on-the-fly from the provided String of raw HTML.
Simple elements without attributes, e.g.,
"<div />"
, are created viadocument.createElement
. All other cases are parsed by assigning the string to the.innerHTML
property of adiv
element. The HTML string cannot contain elements that are invalid within a div, such as html, head, body, or title elements.All HTML must be well-formed, otherwise it may not work correctly across all browsers. This includes the case where
$("<span>")
may not work but$("<span/>")
will (note the XML-style closing slash).
I can't say for certain, but performance wise the second option:
$("<span class=\"foo\"></span>");
is generally better because there's no extra string concatenation (i.e. adding the "class='foo'" into matching span tags.
You also have the benefit of viewing it in the source using the default FF/IE/OPERA/ETC source viewers, whereas you'll need to look at a live view of the DOM to see the result of this:
$("<span>").addClass("foo")
Pick the second option - static HTML carries a minor performance benefit but more importantly a serious readability benefit that will help you when you ultimately hit 'View Source' to try and figure out why your elements aren't showing up as desired.
First create a div element like the following:
<div id="test"></div>
Then you can easily do this using the following code:
$("<span class=\"foo\"></span>").appendTo("div#test");
You can also use any other html element such as table instead of div.
Hope this would help you.