Skip to content Skip to sidebar Skip to footer

Difference Between $('selector') And $('selector')[0] In Jquery

Assuming i have a
,Please consider the following: var m = $('.test')[0]; var $md = $(m); console.log($md.width()); //200 v

Solution 1:

Here you get the first element matched selector, it returns plain js instance.

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

Here you wrap it in a jQuery object again.

var $md = $(m);

Since width() method return width of the first element in set there is no difference between approach, until you've got a multiple .test elements on a page and want to change them like this:

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

This code will set the width of each .test element on a page to 100px.

But this continue to change only first matched element in a set:

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

There are synthetic examples based on your code, i think it's better to write this way:

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

or

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

Post a Comment for "Difference Between $('selector') And $('selector')[0] In Jquery"