My goal is to replicate the normal jQuery each type function from scratch using only Javascript. Here is my code so far:
// Created a jQuery like object reference
function $(object) {
return document.querySelectorAll(object);
this.each = function() {
for (var j = 0; j < object.length; j++) {
return object[j];
}
}
}
console.log($('.dd')); // returns NodeList[li.dd, li.dd]
$('.opened').each(function() {
console.log(this);
}); // Results in an error [TypeError: $(...).each is not a function]
As you can see, each is showing as a error. How should I go about fixing this?
A lightweight class that works like that would be:
function $(selector) {
// This function is a constructor, i.e. mean to be called like x = new $(...)
// We use the standard "forgot constructor" trick to provide the same
// results even if it's called without "new"
if (!(this instanceof $)) return new $(selector);
// Assign some public properties on the object
this.selector = selector;
this.nodes = document.querySelectorAll(selector);
}
// Provide an .each function on the object's prototype (helps a lot if you are
// going to be creating lots of these objects).
$.prototype.each = function(callback) {
for(var i = 0; i < this.nodes.length; ++i) {
callback.call(this.nodes[i], i);
}
return this; // to allow chaining like jQuery does
}
// You can also define any other helper methods you want on $.prototype
You can use it like this:
$("div").each(function(index) { console.log(this); });
The pattern I 've used here is widely known (in fact jQuery itself also uses it) and will serve you well in a great many cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With