Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the correct or better way to create a new element with jQuery?

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?

like image 293
Vixed Avatar asked Feb 15 '16 15:02

Vixed


People also ask

Which jQuery method is used to style an element?

css() method: The css() method is used to change the style property of the selected element. The css() in JQuery can be used in different ways.

Which is the correct syntax for select all elements in jQuery?

Explanation: The $("*") selector is used to select all elements. 18. Which is the correct jQuery selector to select current HTML element?


2 Answers

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"

like image 198
Quentin Avatar answered Sep 20 '22 15:09

Quentin


taking a look into the jQuery library, the following is the relevant section from v2.2.0 line 2827.

init = jQuery.fn.init = function(selector, context, root) {
    var match, elem;

    // HANDLE: $(""), $(null), $(undefined), $(false)
    if (!selector) {
      return this;
    }

    // Method init() accepts an alternate rootjQuery
    // so migrate can support jQuery.sub (gh-2101)
    root = root || rootjQuery;

    // Handle HTML strings
    if (typeof selector === "string") {
      if (selector[0] === "<" &&
        selector[selector.length - 1] === ">" &&
        selector.length >= 3) {

        // Assume that strings that start and end with <> are HTML and skip the regex check
        match = [null, selector, null];

      } else {
        match = rquickExpr.exec(selector);
      }

      // Match html or make sure no context is specified for #id
      if (match && (match[1] || !context)) {

        // HANDLE: $(html) -> $(array)
        if (match[1]) {
          context = context instanceof jQuery ? context[0] : context;

          // Option to run scripts is true for back-compat
          // Intentionally let the error be thrown if parseHTML is not present
          jQuery.merge(this, jQuery.parseHTML(
            match[1],
            context && context.nodeType ? context.ownerDocument || context : document,
            true
          ));

          // HANDLE: $(html, props)
          if (rsingleTag.test(match[1]) && jQuery.isPlainObject(context)) {
            for (match in context) {

              // Properties of context are called as methods if possible
              if (jQuery.isFunction(this[match])) {
                this[match](context[match]);

                // ...and otherwise set as attributes
              } else {
                this.attr(match, context[match]);
              }
            }
          }

          return this;

You will see that it checks if the selector is a string, and if it does then see's if it starts with < and ends with >.

if (typeof selector === "string") {
  if (selector[0] === "<" &&
    selector[selector.length - 1] === ">" &&
    selector.length >= 3) {

Then, having in mind the regex rsingleTag being:-

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

Which matches both "<div>" and "<div />", returning div as group[1].

The parseHTML uses that to return a div element, in the merge:-

jQuery.parseHTML = function( data, context, keepScripts ) {

    ...

    var parsed = rsingleTag.exec( data );

    // Single tag
    if ( parsed ) {
        return [ context.createElement( parsed[ 1 ] ) ];
    }

then using the regex again, and context as your object for setting the properties:-

// HANDLE: $(html, props)
if (rsingleTag.test(match[1]) && jQuery.isPlainObject(context)) {

it for's over each property setting with this.attr(match, context[match]);

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

As above shows, its personal preference. Both work the same.

like image 45
BenG Avatar answered Sep 21 '22 15:09

BenG