There are a few problems here.
- When you call jQuery with an array (like you're doing), jQuery expects it to be an array of DOM elements.
- If you want to use
$.each, use the static version that iterates over generic objects or arrays.
With both of those things said, there's stil an issue with using $.each with an array containing primitive values. The following code exhibits the same problem you were seeing:
$.each([".b"], function () {
console.log($('.a').find(this).text()); // Expecting to print "Test"
});
Inside the callback function for .each, this is a String object and not a string primitive. To understand this, we need to look at what .each is doing under the hood:
for (; i < length;) {
if (callback.apply(object[i++], args) === false) { // <----
break;
}
}
The important bit is the call to apply. According to the ECMAScript specification, when a primitive value is passed to apply, the value's toObject method is called:
If thisArg is null or undefined, the called function is passed the global object as the this value. Otherwise, the called function is passed ToObject(thisArg) as the this value.
This explains why your code was not working-- .find expects a string primitive and not a String object.
This is why the documentation for $.each actually mentions using this with primitive values:
(The value can also be accessed through the this keyword, but Javascript will always wrap the this value as an Object even if it is a simple string or number value.).
Therefore the way to fix the problem with your code is to leverage the element argument that's passed to the callback function:
$.each([".b"], function (_, item) {
console.log($('.a').find(item).text()); // Expecting to print "Test"
});
['.b']means?$.eachcan be used to loop over arrays or objects