$('<element>') vs $('<element />') in jQuery

I see people creating HTML elements in jQuery in two different ways:

$('<element>')

and

$('<element />') 

I am curious which one is "more correct". I see the obvious advantage to the first one as being just simply less to type. Does it make a difference at all which one is used?


There is no difference, as seen in the source code, line 30 & line 121:

/* Line 30*/
rsingleTag = /^<(w+)s*/?>(?:</1>)?$/,

/* Line 121 */
// If a single string is passed in and it's a single tag
// just do a createElement and skip the rest
ret = rsingleTag.exec( selector );

The following are equivalent:

  • <a></a>
  • <a />
  • <a>

  • Technically $('<element></element>') is more correct, since self closing tags using / was removed in HTML5, however it makes absolutely no difference, because that statement is parsed by jQuery. If anything, just using $('<element>') might actually be slightly faster, because it's less chars to read. Which should skip some Regex conditions as well.

    Better yet, if you're looking for the fastest possible way using jQuery:

    var temp = new jQuery.fn.init();
    temp[0] = document.createElement('element');
    temp.length = 1;
    

    This version is fastest, because it skips jQuery() which wraps "new jQuery.fn.init()", and passes no arguments so that it immediately returns a new jQuery object. It skips a lot of conditions and fail-safe statements, that are unnecessary if you already know exactly what you're trying to do.

    Or slightly shorter:

    var temp = $(document.createElement('element'));
    

    This version is slightly slower, but much easier to read, and a lot neater. It still skips a big chunk of code used to parse the, what would be a string being passed. Instead, jQuery can just automatically know we're working with a node here.

    Reference
    HTML5 Does NOT Allow “Self-Closing” Tags
    Google: html5 self closing tags
    jsperf


    No, it makes no difference at all, as long as the element definition is well-formed. The second style is simply an alternate syntax which can actually save keystrokes:

    $('<a href="herp.derp.com/sherp"/>');    // XML-like syntax
    $('<a href="herp.derp.com/sherp"></a>'); // Well-formed HTML
    $('<a href="herp.derp.com/sherp">');     // Malformed (no closing tag)
    
    链接地址: http://www.djcxy.com/p/83354.html

    上一篇: 动态创建<div>的JavaScript

    下一篇: $('<element>')与$('<element />')在jQuery中