誰が使うんだろうかこれ?
function $$(sel) { var self = this; var type = /^#(\w+)$|^\/\/(.*?)$|^\.(\w+)$|^(\w+)$/; sel.replace(type, function($0, $1, $2, $3, $4) { if($1) { self.elm = []; self.elm.push(document.getElementById(sel.replace('#', ''))) } else if($2) { self.elm = []; var x = document.evaluate(sel, document, null, XPath.ORDERED_NODE_SNAPSHOT_TYPE, null); for(var i = 0; i < x.snapshotLength; i++) { self.elm.push(x.snapshotItem(i)); } } else if($3) { self.elm = []; var tmp = document.getElementsByTagName('*'); var class = sel.replace(/^\./, "") for(var i = 0; i < tmp.length; i++) { if(tmp[i].className == class) { self.elm.push(tmp[i]); } } } else if($4) { self.elm = document.getElementsByTagName(sel) } }); this.e2a(); return this; } $$.prototype.e2a = function() { this.length = this.elm.length; for(var i = 0, len = this.length; i < len; i++) { this[i] = this.elm[i]; } this.first = this[0] this.end = this[this.length - 1] } $$.prototype.each = function(func) { for(var i = 0; i < this.length; i++) { func(this[i]); } return this; } $$.prototype.filter = function(func) { this.elm = []; for(var i = 0; i < this.length; i++) { if(func(this[i])) { this.elm.push(this[i]); } } this.e2a(); return this; } var $ = function(x) { return $[x] || ($[x] = new $$(x)); }
使いかた
$('p').each(function(i) { i.style.background = '#000' } // p要素全ての背景を黒に $('#hoge')[0] // id が hoge の要素を。 $('.fuga').filter(function(i) { return i.tagName == 'P'; }).each(function(i) { i.style.color = 'blue'; } // class が fuga で P 要素であれば 文字色を青に。 $('//p') // xpath も使える。
気が向いたら拡張する。 なんか for ループばっかで気持ち悪い。
おまけ: デバッグ用
function log() { var res = Array.apply(null, arguments).join(", ") if(window.opera) { opera.postError(res); } else if (window.console) { console.log(res); } else { alert(res); } }