JavaScript plugin creation

javascript, plugins

Solution

You can create your own wrapper (similar to jQuery), and doing this will allow you to circumvent all of the discussed problems with extending the DOM directly.

myWrapper = (function(){

    function NodeList(elems) {

        this.length = 0;
        this.merge(this, elems.nodeType ? [elems] : elems);

    }

    function myWrapper(elems) {
        return new NodeList(elems);
    }

    myWrapper.NodeList = NodeList;

    NodeList.prototype = {
        merge: function(first, second) {

            var i = first.length, j = 0;

            for (var l = second.length; j < l; ++j) {
                first[i++] = second[j];
            }

            first.length = i;

            return first;

        },
        each: function(fn) {

            for (var i = -1, l = this.length; ++i < l;) {
                fn.call(this[i], this[i], i, l, this);
            }

            return this;

        }
    };

    return myWrapper;

})();

And you can add your own methods like so:

myWrapper.NodeList.prototype.myPlugin = function() {
    return this.each(function(){
        // Do something with 'this' (the element)
    });
};

Usage:

myWrapper(document.getElementById('id')).myPlugin();

Problem

How to create a pure JavaScript (without using any library) plugin which looks like: ``` document.getElementById('id').myPlugin(); ``` Like jQuery?

Original source