开发者

jQuery: When creating a new element, do I need the ending tag?

var $div = $('<div class="error">').appendTo($('#header'));

When creating new elements and adding them to the DOM, do you need the ending tag? why or why not? Do I only need the ending tag if i'm placing content into the tag i'm creating开发者_Python百科? like so:

var $div = $('<div class="error"> Error-Homie! </div>').appendTo($('#header'));

or could I create an element with content in it, but leave out the ending tag? Good? Bad?

var $div = $('<div class="error">').appendTo($('#header'));


Although it may work if you don't use a closing tag (or at least self close the tag), you should add a closing tag (self-close) (as mentioned, for cross-platform compatibility):

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

This is how jQuery creates the elements:

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.


Btw. you can also pass the data as second parameter:

$('<div />', {'class': 'error', text: 'Error-Homie!'})


you need the ending tag : http://api.jquery.com/appendTo/ for example

$('<p>Test</p>').appendTo('.inner');

it should also be

.appendTo('#header');

and not

.appendTo($('#header'));


you can probably do it like this

$('<div/>',{class:'error'}).html('Error-Homie!').appendTo($('#header'));


You always need the ending tag to have proper html.

But it is a fact that the majority of browsers let such mistakes slip. It's no reason to be lazy, though, you should not rely on the browsers' tolerance for your code to work. This tolerance is there to be able to display sites with a few mistakes, not to caution deliberately incorrect code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜