I'm trying to create some helper functions like what jQuery does but in vanilla JS.
This is what I have;
var $ = function(selector){
var elements = typeof selector == 'string' ? document.querySelectorAll(selector) : selector;
elements.each = function(){
this.forEach(function(item, index){
var element = _(this[index]);
//How do I apply the passed in function to this element??
})
};
}
It is used as such;
var x = 0;
$('.field').each(function(e){
e.addClass('item-' + x);
x++;
});
How do I use the function I am passing in above into the $ object and apply it to the passed in element?
There are A LOT of questions asked around this but not for my specific issue, and I couldn't modify them to suit my situation. Any help is appreciated.
Although epascarello posted a way to lay out the chaining you want to accomplish, I wanna also bring up that the current way you have things set up are contradictory.
One being that you define an each() method on the elements variable you create, and two being that you define the each() method to take no parameters, but then you go on to pass a function as a parameter when you're using the method. Also the way you are referencing the elements you queried is somewhat messed up.
I think you should instead restructure your code into something like:
const $ = function(selector){
let elements;
let bundle = {
get(selector){
return typeof selector == 'string' ? document.querySelectorAll(selector) : selector;
},
each(executor) {
// instead of calling forEach on 'this', call it on the elements instead
// thanks to closures, this each() method still has access to the elements that were queried
elements.forEach(function(item, index){
let tempEle = item;
// you can call the passed executor function here
executor();
});
}
}
elements = bundle.get(selector);
return bundle;
}
So you could then call it as below, where you send in an executor function to be applied each iteration thru the forEach() loop defined within each()
$('.field').each(() => {
console.log("Calling in the each() method");
});