jquery like function get element

393 views Asked by At

I want to build a library, that is similiar to jquery

example of calling the function

$('#myDiv');
$('#myDiv').hide();

I am using a template from here

            (function () {
            var Q = function (params) {
                return new Library(params);
            };
            var Library = function (params) {
                var selector = document.querySelectorAll(params),
                    i = 0;
                this.length = selector.length;
                for (; i < this.length; i++) {
                    this[i] = selector[i];
                }
                return this;       
            };
            Q.fn = Library.prototype =
            {
                hide: function () {
                    var len = this.length;
                    while (len--) {
                        this[len].style.display = 'none';
                    }
                    return this;
                },
                show: function () {
                    var len = this.length;
                    while (len--) {
                        this[len].style.display = 'block';
                    }

                    return this;
                }   
            };
            if(!window.Q) {
                window.Q = Q;
            }
        })();

It works perfectly But if I want to get an HTML-Element by selector I have to call

$('#myDiv')[0] // Returns the element

instead of calling

$('#myDiv') // Returns an object

How can I get my element without the annoying '[0]' by default?

1

There are 1 answers

0
Aravind On

I admit it was a bit of a challenge for me, though I had said it casually in the comment.

Things to ponder: You want $ to return an object that has both a value and some helper functions. It sucks to have to write new $() to create an object, so I abstracted the object creation into the $ function, so that the $ function will take an id, and create an object with two things: a value which equals the document.getElementByID() object, and some helper functions.

Here you go:

var $ = function(x){
    var helpers = { /* write your helper functions here, remember this.value is the DOM object*/
    setColor: function(col){
   (this.value).setAttribute("color",col);     
}};
    function f(x){ this.value = document.getElementById(x);};
    f.prototype = helpers;
    return new f(x);
};

$('q').setColor("red");