4

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.

5
  • What do you expect from (".c", $html);? Commented Nov 15, 2013 at 18:23
  • @j08691 I am expecting a jquery object containing the elements with class c, so in this case the two inner div elements. Commented Nov 15, 2013 at 18:25
  • 2
    But without the $ in front of the parenthesis, it's not a jQuery object. Only the $html inside is a jQuery object, the rest is ignored. You could have ("foo", $html); and still get a result of 1. Commented Nov 15, 2013 at 18:28
  • 1
    ("comma operator claims another victim", $html) Commented Nov 15, 2013 at 18:30
  • @j08691 You are totally right, its just a missing $. waaaah Commented Nov 15, 2013 at 18:35

2 Answers 2

4

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

while

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

Sign up to request clarification or add additional context in comments.

2 Comments

I'm sorry but I am not understanding your explanation, could you elaborate a little bit.
first statements considers outer (parent div only) because you have not used $. whereas second statement considers number of elements having class c. you got it?
3

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/

1 Comment

That comment mixed with your name made me smile :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.