// works like $('#id') but do $('id')var$=document.getElementById.bind(document);// works like $('.class') but do $$('.class')var$$=document.querySelectorAll.bind(document);
// for an arrayfunctioneach(arr,fn){for(variinarr){fn(i,arr[i]);}}// for dom element, works like $.eachvarelements=document.querySelectorAll(selector);Array.prototype.forEach.call(elements,function(el,i){// your action});
// classList is much faster than className as we know, ref: http://t.cn/RAYkuEr// addClassfunctionaddClass(el,className){if(el.classList)el.classList.add(className);elseel.className+=' '+className;}// removeClassfunctionremoveClass(el,className){if(el.classList)el.classList.remove(className);elseel.className=el.className.replace(newRegExp('(^|\\b)'+className.split(' ').join('|')+'(\\b|$)','gi'),' ');}// toggleClassfunctiontoggleClass(el,className){if(el.classList){el.classList.toggle(className);}else{varclasses=el.className.split(' ');varexistingIndex=classes.indexOf(className);if(existingIndex>=0)classes.splice(existingIndex,1);elseclasses.push(className);el.className=classes.join(' ');}}
Trim
// works like $.trim(string)varstring=' ai shi te ru ';string.trim();// print 'ai shi te ru'
Get element offset
functiongetOffset(el){var_x=0;var_y=0;while(el&&!isNaN(el.offsetLeft)&&!isNaN(el.offsetTop)){_x+=el.offsetLeft-el.scrollLeft;_y+=el.offsetTop-el.scrollTop;el=el.offsetParent;}return{top: _y,left: _x};}// example: var offset = getOffset(document.getElementById('yourElId'));
Check
// detect browsersvarisOpera=!!window.opera||navigator.userAgent.indexOf(' OPR/')>=0;// Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)varisFirefox=typeofInstallTrigger!=='undefined';// Firefox 1.0+varisSafari=Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor')>0;// At least Safari 3+: "[object HTMLElementConstructor]"varisChrome=!!window.chrome&&!isOpera;// Chrome 1+varisIE=/*@cc_on!@*/false||!!document.documentMode;// At least IE6
Cookie
// ref: https://github.com/filamentgroup/cookiefunctioncookie(name,value,days){// if value is undefined, get the cookie valueif(value===undefined){varcookiestring="; "+window.document.cookie;varcookies=cookiestring.split("; "+name+"=");if(cookies.length===2){returncookies.pop().split(";").shift();}returnnull;}else{// if value is a false boolean, we'll treat that as a deleteif(value===false){days=-1;}varexpires;if(days){vardate=newDate();date.setTime(date.getTime()+(days*24*60*60*1000));expires="; expires="+date.toGMTString();}else{expires="";}window.document.cookie=name+"="+value+expires+"; path=/";}}
Flatify an array
vararr=[1,2,[3,[4,5]],6]varresult=[]varflat=function(arr){vari,l=arr.lengthfor(i=0;i<l;i++){if(typeofarr[i]==='number'){result.push(arr[i])}else{flat(arr[i])}}returnresult}arr=flat(arr)// result is [1,2,3,4,5,6]
Parse url
// parse url queries to an array, http://example.com/?q=words&ord=desc => ['words', 'desc']varquery=location.search.substring('1').split('&')for(variinquery){query[i]=query[i].split('=')[1]}// parse url queries to an object, http://example.com/?q=words&ord=desc => {q: 'words', ord: 'desc'}varquery=location.search.substring('1').split('&')varparams={}for(variinquery){varkey=query[i].split('=')[0],value=query[i].split('=')[1]params[key]=value}
Get number between $start and $end
// NumberBetween(0, 100) return a ( 0 <= number < 100 )functionNumberBetween(start,end){returnMath.floor(Math.random()*end)+start}
// I haven't checked thisfunctionrandomDivs(el){varnewDivs=[]for(vari=0,dom=document.querySelectorAll(el);i<dom.length;i++){varrandomIndex=NumberBetween(0,dom.length)newDivs[newDivs.length]=dom[randomIndex].cloneNode(true)dom[randomIndex].parentNode.removeChild(dom[randomIndex])}returnnewDivs}
Count words with CJK support
varstring='我爱你,你呢? me too!'varcount=string.match(/[\u00ff-\uffff]|\S+/g).length//returns 9