title: tiny implementation of jquery
body: <p>1) I have a task to implement jQuery on Javascript.
  But for some reason my method each doesn't work.
  For example when i write</p>
  
  <pre><code>$('.a').each(function (index) {$(this).append('&lt;b&gt;' + index + '&lt;/b&gt;')})
  </code></pre>
  
  <p>it returns </p>
  
  <p>DOMException: Failed to execute 'querySelectorAll' on 'Document': '[object Object]' is not a valid selector.</p>
  
  <p>also I can't use <code>this.each</code> inside of other functions. For example if I would have used each instead of <code>forEach</code> inside append it would have not worked.</p>
  
  <hr>
  
  <pre><code>&lt;script type="text/javascript"&gt;
  (function() {
    function $(selector) {
      if (this instanceof $) return this.search(selector)
        return new $(selector);
    }
    $.prototype = {
      constructor: $,
      length: 0,
  
      search: function(selector) {
        var that=this;
        var elems=Array.prototype.slice
            .call(document.querySelectorAll(selector));
        elems.forEach(function(x,i){that[i]=x;});
        this.length = elems.length;
        return this;
      },
  
      append: function(text) {
        if (text instanceof $) {
          this[0].appendChild(text[0]);
          for(var i = 1; i &lt; this.length-1; i++) {
            var p = text[0].cloneNode(true);
            this[i].appendChild(p);
          }
        } else Array.prototype.slice
            .call(this).forEach(function(x){
                x.innerHTML  =  x.innerHTML  +  text;
            });
  
        return this;
      },  
  
      each: function(callback){
        for (var i=0;i&lt;this.length;i++){
          this[i]=callback.call(this,this[i])
        };
        return this;
      },
  
    }
    window.$ = $;
  }());
  </code></pre>
  
  <p></p>