1

I'm creating javascript library like jQuery, I have successfully adding prototype html() but if I call it with $(selector) it return object like {'el' : [array]} and if change in function to return this.el; it return array but I can't call .html().

How it can return [array] instead without breaking prototype?

window.$ = function(selector) {
  if (!(this instanceof $)) {
    return new $(selector);
  }
  this.el = [];
  this.html = function(str) {
    this.el.forEach(function(el) {
      el.innerHTML = str;
    });
  };

  (function(self) {
    for (var eList = document.querySelectorAll(selector), i = eList.length - 1; i > -1; i--) {
      self.el[i] = eList[i];
    }
  })(this);
 
  return this;
};

$('#test').html('BBBBB')
console.log($('#test')[0])
<div id="test">AAAAAAA</div>

2 Answers 2

1

 window.$ = function(selector) {
      var x = [];
      x = document.querySelectorAll(selector);
      console.log(x);
      return x;
    };
NodeList.prototype.html = function(str) {
	console.log(this);
	this.forEach(function(el){
    	el.innerHTML = str;
    });
}


console.log($('#test').html('BBBBB'))
<div id="test"></div>

I extended the html method inside the NodeList array. tell me if it can fit you.

Sign up to request clarification or add additional context in comments.

1 Comment

like jQuery it should return array if I call $('#test') not $('#test').el.....
1

finally it solved by looking Zepto source code, the magic to convert object to array is you have to create $.prototype.splice, it copied from the Array.splice

class return array

// only load if no jQuery on the page
if (window.$ === undefined) window.$ = (function () {
    var $, zepto = {}, emptyArray = [];

    function Z(dom, selector) {
        var i, len = dom ? dom.length : 0;
        for (i = 0; i < len; i++) this[i] = dom[i];
        this.length = len;
        this.selector = selector || '';
    }
    Z.prototype = {
        splice: emptyArray.splice,
        forEach: emptyArray.forEach,
        html: function (str) {
            this.forEach(function (el) {
                el.innerHTML = str;
            });
        }
    };
    zepto.Z = function (dom, selector) {return new Z(dom, selector);};
    zepto.init = function (selector, context) {
        if (!selector) return zepto.Z();
        var dom = document.querySelectorAll(selector);
        return zepto.Z(dom, selector);
    };
    $ = function (sel, ctx) {return zepto.init(sel, ctx); };

    return $;
})();

$('.test').html('DDDDD');
console.log($('.test'));
<div class="test"> AAAA </div>
<div class="test"> BBBB </div>
<div class="test"> CCCC </div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.