jQuery returns only the first object by given sele

2019-09-16 12:30发布

问题:

As you know, jQuery always return an array of objects by given selector (e.g: $(‘a')), it works well for my previous projects. Recently we move to ES6 + webpack, $(‘a’) only returns the first object, instead of the whole array, strange, does any guys have the same experience? or any change for jQuery, es6 and webpack? Please share and thanks in advance.

PS: jQuery version V2.2.4, node version V6.3.1 for webpack projects.

回答1:

jQuery selector does not return an Array object. Instead it returns a custom jQuery object that behaves like an array.

You can access the entries using subscript ($('a')[5]) and it also has a property called length that reflects its size, but it is not of Array type.


For example: var list = $('a');

list will then be: jQuery.fn.init[234] where 234 happens to the number of elements the selector matched.

Then doing a typeof list returns "object". Even if it matched only one element, it will still act like an Array, having a size of 1.


However, you can turn it into an Array by using the jQuery.makeArray(obj) function.

For example: var array = $.makeArray(list) will turn it into Array which will return true when you call $.isArray(array) on it.