6

Possible Duplicate:
$(‘<element>’) vs $(‘<element />’) in jQuery

I am used to write $('<div>').
But today I saw a presentation about advanced-jquery by john-resig who use the following syntax $('<div/>').
http://loft.bocoup.com/john-resig-advanced-jquery/

To me they seem to produce the same output.

My question is: is there some difference between $('<div>') and $('<div/>')?

Community
  • 1
  • 1
Lorraine Bernard
  • 13,000
  • 23
  • 82
  • 134

3 Answers3

7

No, jQuery will normalize those statements into the exact same.


In some earlier version of jQuery tho, it happend to be that <div> was actually faster than <div/> for whatever reason. I don't know yet, if that still applies.

http://jsperf.com/jquery-constructor-performance

Seems like this bug/feature is no longer true.

jAndy
  • 231,737
  • 57
  • 305
  • 359
5

<div>, <div/>, <div></div>, and even <div/></div> (Yes, this one will only create one element) all trigger the singleTag regular rexpression which makes jQuery to call document.createElement("div"). It was never passed to any html parser at all.

Here's the regex that you can play with, if it returns true, it will be document.createElement'd

var rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/;
Esailija
  • 138,174
  • 23
  • 272
  • 326
4

<div> is an opening tag. <div/> is a self-closing tag. In this context, however, there is no difference.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • 1
    Self-closing tags *do not exist* in HTML. They're allowed in HTML 5, in order to appease people who just can't let XHTML die, but they don't self close. You can't say `
    ` in real HTML and have it work like XHTML weenies expect -- the parser ignores the slash, and treats `
    ` just like `
    `.
    – cHao Dec 12 '12 at 17:19
  • OK, upon rereading [the spec](http://www.whatwg.org/specs/web-apps/current-work/#elements-0), i take it back. Self-closing tags do semi exist, but only for "foreign elements" (MathML/SVG), and for void elements (which don't have an end tag anyway). It seems `
    ` is actually invalid HTML.
    – cHao Dec 12 '12 at 17:52