, please pa...">

Difference between $ ('selector') and $ ('selector') [0] in jquery

Assuming that I have <div class="test" style="width:200px"></div>, please pay attention to the following:

var m = $('.test')[0];
var $md = $(m);
console.log($md.width()); //200

var o = $('.test');
console.log(o.width());  // 200


console.log(m);   // <div class="test" style="width:200px">
console.log($md);  // Object{ context: <div.test> ..... } 
console.log(o);   // Object{ length:1 , ..... }

Basically, I can apply the method widthto var $mdor var o, so what is the difference between the 1st and 2nd methods, if the output is the same?
I see that both mdare and oare objects, but at the console output they are not quite the same, how do they differ? thank.

+4
source share
1 answer

Here you get the first element matched by the selector, it returns a regular js instance.

var m = $('.test')[0]; 

Here you wrap it again in the jQuery object.

var $md = $(m);

width() , , .test :

 $('.test').width(100)

.test 100 .

:

 var el = $('.test')[0];
 $(el).width(100);

, , , :

$('.test').first().width(100);

$('.this:first').width(100);
+3

Source: https://habr.com/ru/post/1667644/


All Articles