Possible Duplicate:
$('<element>') vs $('<element />') in jQuery
Which one of these two are the correct way to do it:
$('<div>')
or
$('<div />')
They both seem to work. Is one way more right than the other, or do they both always work?
Possible Duplicate:
$('<element>') vs $('<element />') in jQuery
Which one of these two are the correct way to do it:
$('<div>')
or
$('<div />')
They both seem to work. Is one way more right than the other, or do they both always work?
From the docs:
If a string is passed as the parameter to $(), jQuery examines the string to see if it looks like HTML (i.e., it has
<tag ... >
somewhere within the string). If not, the string is interpreted as a selector expression, as explained above. But if the string appears to be an HTML snippet, jQuery attempts to create new DOM elements as described by the HTML. Then a jQuery object is created and returned that refers to these elements. You can perform any of the usual jQuery methods on this object:
$('<p id="test">My <em>new</em> text</p>').appendTo('body');
If the HTML is more complex than a single tag without attributes, as it is in the above example, the actual creation of the elements is handled by the browser's innerHTML mechanism. In most cases, jQuery creates a new element and sets the innerHTML property of the element to the HTML snippet that was passed in. When the parameter has a single tag, such as
$('<img />') or $('<a></a>')
, jQuery creates the element using the native JavaScript createElement() function.
To ensure cross-platform compatibility, the snippet must be well-formed. Tags that can contain other elements should be paired with a closing tag:
$('<a href="http://jquery.com"></a>');
Alternatively, jQuery allows XML-like tag syntax (with or without a space before the slash):
$('<a/>');
Tags that cannot contain elements may be quick-closed or not:
$('<img />');
$('<input>');
They produce identical results in jQuery.
Though it seems they produce identical result, but based on uses they might not generate same result. For example:
While jQuery parse $('<div> <p>')
, the <p>
tag will be a children of the<div>
tag, so the result would be: <div> <p></p> </div>
And while jQuery parse $('<div/> <p/>')
, the <p/>
tag will be a sibling of the <div/>
tag, so the result would be: <div></div> <p></p>
Both variants give you same result but this
$('<div />', {id:"myID",class:"mycssClass class2 clazzz",some-attribute: "value"});
is better, more readable than
$('<div id="myId" class="mycssClass class2 clazzz" some-attribute="value"></div>');