Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attempt to create a each() type jQuery function using Javascript from scratch

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?

like image 875
Shivam Avatar asked Jun 01 '26 15:06

Shivam


1 Answers

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.

like image 59
Jon Avatar answered Jun 04 '26 11:06

Jon