doll.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. ;(function(){ // jQuery shim
  2. if(window.$){ return }
  3. (($ = window.$ = function(q, tag){
  4. if(!(this instanceof $)){ return new $(q, tag) }
  5. this.tags = (q && q.tags) || (('string' != typeof q)?
  6. (q?[q]:[]) : (tag||document).querySelectorAll(q));
  7. return this;
  8. }).fn = $.prototype).each = function(cb){ return $.each(this.tags, cb), this }
  9. $.each = function(o, cb){ Object.keys(o).forEach(function(k){ cb(k, o[k]) }) }
  10. $.fn.get = function(i, l, u){ return l = this.tags, (i === u)? l : l[i] }
  11. $.fn.on = function(eve, cb){ return this.each(function(i, tag){ tag.addEventListener(eve, cb) })}
  12. $.fn.is = function(q, b){ return this.each(function(i, tag){ b = b || tag.matches(q) }), b }
  13. $.fn.css = function(obj){ return this.each(function(i, tag){ $.each(obj, function(k,v){ tag.style[k] = v }) })}
  14. $.fn.text = function(text, key, f, u){
  15. text = (text === u)? '' : (f = 1) && text;
  16. key = key || 'textContent';
  17. this.each(function(i, tag){
  18. if(f){ tag[key] = text }
  19. else { text += (tag[key]||'') }
  20. });
  21. return f? this : text;
  22. }
  23. $.fn.html = function(html){ return this.text(html, 'innerHTML') }
  24. $.fn.find = function(q){
  25. var I = $(), l = I.tags;
  26. this.each(function(i, tag){
  27. $(q, tag).each(function(i, tag){
  28. if(0 > l.indexOf(tag)){ l.push(tag) }
  29. });
  30. });
  31. return I;
  32. }
  33. $.fn.add = function(html, div){
  34. (div = document.createElement('div')).innerHTML = html;
  35. this.tags = [].slice.call(this.tags).concat([].slice.call(div.childNodes));
  36. return this;
  37. }
  38. $.fn.append = function(html, op, f){ return this.each(function(i, tag){
  39. (('<' === html[0])? $().add(html) : $(html)).each(function(i, node){
  40. (f? node : tag)[op || 'appendChild'](f? tag : node);
  41. })
  42. })}
  43. $.fn.appendTo = function(html){ return this.append(html, 0, 1) }
  44. $.fn.parents = function(q, c){
  45. var I = $(), l = I.tags, p = 'parentElement';
  46. this.each(function(i, tag){
  47. if(c){ (c = {})[p] = tag ; tag = c }
  48. while(tag){ if((tag = tag[p]) && $(tag).is(q)){
  49. l.push(tag); if(c){ return }
  50. }}
  51. });
  52. return I;
  53. }
  54. $.fn.closest = function(q, c){ return this.parents(q, 1) }
  55. }());