So I have made the following fiddle:
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 do these two approaches differ?
EDIT:
This is JQuery 1.10.1 by the way.
var $elts = (".c", $html);
considers element (outer) div
while
$elts = $(".c", $(html));
considers divs having .c
.
That's because the first one is not a jquery object :
var $elts = (".c", $html);
Doing (".c", $html)
will only mean the var will equal the last value inside the bracket wich is the jQuery $html object.
Test it, try this
var $elts = ('anything', 4);
console.log($elts) // = 4;
if you do var $elts = $('.c', $html)
, both log will be the same :
http://jsfiddle.net/L3dTK/5/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With