jqueryappendelementnew-operatorend-tag

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

Solution

  • 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!'})