JQuery: risk not closing tags in constructors

Is there any reason why 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.

+5
source share
4 answers

It depends on whether you use one tag or several tags to create an element / elements.

If you use a single tag, jQuery will use the document.createElement method to create the element, so it doesn’t matter whether you use "<div/>" or "<div></div>" .

If you have multiple elements, jQuery will create the elements by creating a div element and putting the HTML in the innerHTML property. In order for the browser to parse the HTML correctly, you must write it in accordance with the version of HTML you are using. If you use XHTML for the page, the HTML you use to create the elements must also be XHTML.

+2
source

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

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

In the second case, however, you add <b> i:

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

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

+5
source

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

At some point, I'm sure the jQuery docs indicate that you should close all your tags. This no longer applies to 1.6, but if you are using 1.3.2 or 1.4.2, you can close them to be safe.

Although, if you look at the source code, I would be tempted that for simple tags it is completely safe. Don’t be afraid that for complex tags or tags with attributes, the source uses .innerHTML , so I highly recommend that you pass correctly closed tags.

A source

 var rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/; ... // If a single string is passed in and it 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 find that ret[1] is a "div", so it calls document.createElement("div") .

+3
source

jQuery does this for you, but consider writing the right HTML for better readability (first in the question) :)

0
source

All Articles