Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapping an html String with JQuery

Tags:

jquery

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.

like image 674
thatidiotguy Avatar asked Mar 22 '23 15:03

thatidiotguy


2 Answers

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

while

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

like image 107
codingrose Avatar answered Apr 07 '23 01:04

codingrose


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/

like image 41
Karl-André Gagnon Avatar answered Apr 07 '23 02:04

Karl-André Gagnon