HTML wrapping with jQuery

So, I made the following script:

http://jsfiddle.net/L3dTK/3/

code:

$(document).ready(function(){
    var html = '<div><div class="c">1</div><div class="c">2</div></div>';
    //approach 1
    var $html = $(html);
    var $elts = (".c", $html);
    console.log($elts.length);
    //approach 2
    $elts = $(".c", $(html));
    console.log($elts.length);  
});

Output:

1
2

Why are these two approaches different?

EDIT:

This is jQuery 1.10.1, by the way.

+4
source share
2 answers

This is because the first one is not a jquery object:

var $elts = (".c", $html);

Execution (".c", $html)will mean that var will be equal to the last value inside the bracket, which is the jQuery $ html object.

Test it try

var $elts = ('anything', 4);
console.log($elts) // = 4;

if you do var $elts = $('.c', $html), both logs will be the same:

http://jsfiddle.net/L3dTK/5/

+3
source

var $elts = (".c", $html); considers an element (external) div

while

$elts = $(".c", $(html));considers divs with .c.

+4
source

All Articles