Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Risk of not closing tags in constructors

Is there any reason I would use $('<div></div>') instead of $('<div>')?

Or $('<div><b></b></div>') instead of $('<div><b>')?

I like the latter in both cases because it is shorter.

like image 600
700 Software Avatar asked May 09 '11 20:05

700 Software


2 Answers

jQuery automaticcally closes the tags for you, there is no need to close it yourself.

$('<div>') is a perfectly fine thing to do

In that second thing however you are appending the <b> i would do:

$('<div>',{html: $('<b>')}); // or $('<div>').append($('<b>')) 

Fiddle: http://jsfiddle.net/maniator/m9wbb/

like image 133
Naftali Avatar answered Oct 12 '22 09:10

Naftali


I've found edge cases in IE where my code was magically fixed by using $("<div></div>") instead of $("<div>"). I always do this out of paranoia.

I'm sure at some point the jQuery docs specifically said you should close all your tags. This is no longer the case with 1.6 but if your using 1.3.2 or 1.4.2 you may want to close them to be safe.

Although if you look at the source code I would be tempted that for simple tags it is perfectly safe. Do be wary that for complex tags or tags with attributes the source uses .innerHTML so I highly recommend you pass in correctly closed tags.

The source

var rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/;

...

// 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);

if (ret) {
    if (jQuery.isPlainObject(context)) {
        selector = [document.createElement(ret[1])];
        jQuery.fn.attr.call(selector, context, true);

    } else {
        selector = [doc.createElement(ret[1])];
    }

} else {
    ret = jQuery.buildFragment([match[1]], [doc]);
    selector = (ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment).childNodes;
}   

In this case with $("<div>") you will find that ret[1] is "div" so it calls document.createElement("div").

like image 23
Raynos Avatar answered Oct 12 '22 10:10

Raynos