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.
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!