On Mon, 27 Aug 2012 19:22:25 -0700, Tim Starling tstarling@wikimedia.org wrote:
On 28/08/12 09:26, Daniel Friesen wrote:
jQuery does special case attribute-less $( '<div />' ) but this is a performance enhancement. The fact that $( '<div>' ) does not break in IE7/IE8 is an unintentional side effect of jQuery's lazy support of special cases like $( '<img>' ) where the tag is self closing and the browser will not require a /.
The performance special case supports both <div> and <div/>:
rsingleTag = /^<(\w+)\s*/?>$/, ... ret = rsingleTag.exec( selector ); if ( ret ) { selector = [ doc.createElement( ret[1] ) ];
The support of <div> is an unintended side effect. Basically jQuery officially supports <div />, <img />, and <img>. Where the non-/> version is only supported for elements that can't have content like img, input, etc... The fact that the createElement special case makes <div> work is a side effect of the /? added to support <img>. It would have been more code to explicitly break the input that they don't officially support.
I think that we should use that special case, and then extend the resulting elements with attr() rather than hitting the innerHTML case. When you specify longer HTML fragments as strings, they tend to get polluted with user input, leading to XSS.
Personally. When it comes to creating a single attribute-less element I'd rather avoid hitting any special magical parsing routines. When you do $( '<div />' ) you go down a pile of tests like "This doesn't look like a selector, right?" "Does this looks like a single element, or a block of html?"
All just to express "Create a <div>". Which you get with document.createElement.
Frankly deal with the "document.createElement( 'div' )" is longer than "$( '<div />' )" and "I want to use jQuery methods on it." arguments I'd prefer having something like `$.tag( 'div' )`.
I still can't believe the high-level jQuery answer after all these years to "Select a div with an id provided by the user" is "Use `$( "div#" + userInput )` and hope there are no special characters. Or find some way to escape it yourself." when low-level dom can just query by ID and there is no reason for jQuery to force people to express everything in querys they parse when they could actually declare portions of a query with object notations.
But it's important to establish conventions which lead the developer down a path where they're less likely to run into trouble, even if they do try to take a few shortcuts. So let's add the slash.
(There is one important case where it's good to use innerHTML: when there are thousands of elements to create in a batch.)
-- Tim Starling