0

jQuery documentation doesn't mention about this case but it's still working. So, I want to mention about them a bit.

var div1 = $("<div></div>");
var div2 = $("<div>");

Both of them create same div tag, so why there is no documentation said that we should use the second for writing code faster?

Imagine if we want to create a template like this:

<div class="parent">
    <div class="child">
        <span>Welcome!<span>
    </div>
</div>

We should do this (1):

$('<div class="parent"><div class="child"><span>Welcome!</span></div></div>');

or (2):

$('<div class="parent"></div>').html($('<div class="child"></div>').html($('<span>Welcome!</span>')));

or (3):

$('<div>').addClass('parent').html($('<div>').addClass('child').html($('<span>').text('Welcome!')));

var span = $('<span>').text('Welcome!'),
    child = $('<div>').addClass('child').html(span),
    parent = $('<div>').addClass('parent').html(child);

As we can see, (3) is very easy to write and read, because we don't need to care about the closing tag.

1

Should we have a tip to use this on the main site? If not, please correct me if there is something wrong while using it.

Thank you!

  • Possible duplicate of [Best way to create nested HTML elements with jQuery](https://stackoverflow.com/questions/11173589/best-way-to-create-nested-html-elements-with-jquery) – chazsolo Apr 08 '18 at 16:43

1 Answers1

0

It is documented in section "Creating New Elements"

When the parameter has a single tag (with optional closing tag or quick-closing) — $( "<img />" ) or $( "<img>" ), $( "<a></a>" ) or $( "<a>" ) — jQuery creates the element using the native JavaScript .createElement() function.

charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • Thanks! I never read it before. I usually use it for all the tags. It still works fine. Maybe I don't understand why we have that quote –  Apr 08 '18 at 16:53
  • I mean: if we can use the short way to create all the tags, so why do we introduce that there is another way (but longer for syntax) to do. Using `$("
    ")` with `addClass`, `prop`, `attr`, `on`.... is enough for everything. No need to write: `$('
    ')`
    –  Apr 08 '18 at 16:58
  • 1
    Right but can also pass in complex html which would need to be valid. The main jQuery function is very versatile. – charlietfl Apr 08 '18 at 16:58
  • Here is a part in the file `dropzone.js`: https://image.ibb.co/gCtiMc/Untitled.png I belive that I never want to use it ^^! –  Apr 08 '18 at 17:03
  • 1
    You never know what you might need in the future....just good to know what you can do – charlietfl Apr 08 '18 at 17:12