最低限の$のDOM操作を実行するためだけのjQueryのようなJavaScript

jQueryの$のDOM操作

最近はjQueryを使用しなくても大半のことはNativeのJavaScriptで記述できるためjQueryの使用頻度はかなり低い。

しかし、jQueryの$などを使用しないとコードが長くなってしまうのが難点だ。

最低限の$のDOM操作を実行

最低限の$のDOM操作を実行できるJavaScriptのコードを作成しておけばjQueryを読み込まなくてもonやattrなどが使用できるようになる。

具体的には使用頻度の高いon, attr, removeAttr, addClass, toggleClass, removeClass, text, html, before, after, prepend, appendの12種だけを使用できるようにする。

コードは以下の通り。

var iwb = function(s) {
  this.value = /^#/.test(s) ?
  [document.getElementById(s.slice(1))] :
  Array.prototype.slice.call(document.querySelectorAll(s));
  return this;
};
var $ = function(selector) {
  return new iwb(selector);
};
iwb.prototype = {
  each: function(fn) {
    [].forEach.call(this.value, fn);
    return this;
  },
  on: function(type, fn) {
    return this.each(function(i) {
      i.addEventListener(type, fn);
    });
  },
  attr: function(a, b) {
    if (b) {
      return this.each(function(i) {
        i.setAttribute(a, b);
      });
    } else {
      return this.value[0].getAttribute(a);
    }
  },
  removeAttr: function(v) {
    return this.each(function(i) {
      i.removeAttribute(v);
    });
  },
  addClass: function(v) {
    return this.each(function(i) {
      i.classList.add(v);
    });
  },
  toggleClass: function(v) {
    return this.each(function(i) {
      i.classList.toggle(v);
    });
  },
  removeClass: function(v) {
    return this.each(function(i) {
      i.classList.remove(v);
    });
  },
  text: function(v) {
    return this.each(function(i) {
      i.textContent = v;
    });
  },
  html: function(v) {
    return this.each(function(i) {
      i.innerHTML = v;
    });
  },
  before: function(v) {
    return this.each(function(i) {
      i.insertAdjacentHTML('beforeBegin', v);
    });
  },
  after: function(v) {
    return this.each(function(i) {
      i.insertAdjacentHTML('afterEnd', v);
    });
  },
  prepend: function(v) {
    return this.each(function(i) {
      i.insertAdjacentHTML('afterBegin', v);
    });
  },
  append: function(v) {
    return this.each(function(i) {
      i.insertAdjacentHTML('beforeEnd', v);
    });
  },
};

圧縮していない状態で1.7KB、圧縮してgzipを使用すれば0.4KBになる。

圧縮したJavaScriptコード

on, attrなどの12種はjQueryとほとんど使い方は同じなので詳細は割愛。