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

末鹿安然 提交于 2021-01-20 04:45:09

问题


Assuming i have a <div class="test" style="width:200px"></div>,Please consider 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 width method on either var $md or var o, so what's the difference between the 1st and 2nd way if the output is the same?
I see that both md and o are objects, but in the console output they not exactly the same, how do they differ? thanks.


回答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);


来源:https://stackoverflow.com/questions/41829233/difference-between-selector-and-selector0-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!