When people create elements with jQuery I always see them do something along the lines of $(<div />)
. Why? As far as I can tell $('<div>')
works just as well. Am I missing something?
It's the syntax for a self-closing tag. A <div>
should not be self-closing, but in this case it makes no difference. jQuery supports it, and it gets rendered the same way.
$("<div>") // = <div></div>
$("<div />") // = <div></div>
$("<div></div>") // = <div></div>
See this SO question for more details:
Why is this jQuery reference '$("<div />")' instead of '$("<div></div>")'?
It never matters.
jQuery (eventually) applies the following regular expression to decide if the string you passed is a "single tag":
/^<(\w+)\s*\/?>(?:<\/\1>)?$/
If the string you pass matches this regex, jQuery simply takes the subpattern (\w+)
(the tag name), and passes it to document.createElement()
.
<div>
, <div />
, <div/>
and <div></div>
all match this pattern, so they're all handled exactly the same: as createElement('div')
.
No you're not missing anything. jQuery will happily take that and render the appropriate tag. I think where a lot of people get tripped up is that the docs suggest you use a XHTML compatible element.
However, what some people seem to miss is that jQuery does not pass that directly to document.createElement()
. Rather, it runs a regex on it (or at least did last time I checked) and figures out what to actually pass to document.createElement()
.
What that suggests to me, is that there is no right or wrong way to create an element, as really, you're passing a string representation of some HTML element. Mr. Resig could have just as easily used $('div');
or $('HTML:DIV');
or whatever he felt like at the time. Instead, he chose to use "HTML like string that will be translated correctly by this regex into actual HTML", and as such all of the following are equally valid:
$('<div>');
$('<div/>');
$('<div></div>');
... and are valid not because they may or may not be XHTML compliant, but because the regex used is able to turn that into a proper HTML element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With