Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do people use slashes when creating elements?

Tags:

jquery

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?

like image 211
George Mauer Avatar asked Oct 12 '11 22:10

George Mauer


3 Answers

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>")'?

like image 83
James Johnson Avatar answered Sep 23 '22 07:09

James Johnson


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').

like image 33
John Flatness Avatar answered Sep 23 '22 07:09

John Flatness


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.

like image 23
Owen Avatar answered Sep 21 '22 07:09

Owen