2

Is $("<div />").appendTo($mySelector) safe to use? Will it work in every browser even though is not a valid HTML element?

I'm asking because it's really easier to use than $("<div><div />")

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
Andre Pena
  • 56,650
  • 48
  • 196
  • 243

3 Answers3

5

Yes. If you look at the source this case is even optimized.

/^<(\w+)\s*\/?>(?:<\/\1>|)$/
  <div      / >               // your case

This regexp will match if there is or is not a /, and it is not included in a group. The only grouped expression is the actual tag name (div), which is used.

If you look more closesly you can see that the following are all handled the very same way:

<div>
<div />
<div></div>
<div /></div>
pimvdb
  • 151,816
  • 78
  • 307
  • 352
0

It will work correctly. jQuery handles the translation.

Grampa
  • 1,623
  • 10
  • 25
0

Yes, but why not use $(document.createElement('div')); it is faster than using the jquery to create the element. It will work without running a regex and requiring translation by jquery.

See this SO answer for a test of using different methods for element creation

Community
  • 1
  • 1
secretformula
  • 6,414
  • 3
  • 33
  • 56
  • 1
    jQuery isn't used becuse it's faster, it's used because it's easier. – Guffa Aug 22 '12 at 20:29
  • ..and you can chain statements – Andre Pena Aug 22 '12 at 20:33
  • you can chain statements off after the inital `document.createElement` thats why its wrapped inside of the `$()` tag. The initial creation is really expensive and using this method is loads faster especially when used inside of loops – secretformula Aug 22 '12 at 20:37