What is the correct or better way to create a new item with jQuery?

advertisements

Related to the answer https://stackoverflow.com/a/10619477/1076753 to cleate an element is better to use

$("<div>", {id: "foo", class: "a"});

or

$("<div />", {id: "foo", class: "a"});

They both works, but which is better or correct to use?

The official API Documentation says that 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>" );

while Tags that cannot contain elements may be quick-closed or not:

$( "<img>" );
$( "<input>" );

So, at the end it's wrong to use one of the first two options for a div?


If you go solely by metrics that can be easily measured: The first is better because it is 2 bytes shorter.

Once you start accounting for readability and other less tangible considerations, it becomes largely a matter of opinion.

So, at the end it's wrong to use one of the first two options for a div?

No, that section only applies "If the HTML is more complex than a single tag without attributes"