看了下jquery的源码,特意分析下其中的隐式链的实现方式。
<div id="box" class="sd dd">box</div> <div id="box2">box</div> <p>fwef</p> <p>fwef</p> <p>fwef</p> <p>fwef</p> <p>fwef</p> <p class="sd dd">fwef</p> <script type="text/javascript"> function $(){ return new YY(); }; function getClassName(name,context){ var arr=[],e,patter=new RegExp(name); context=context||document; e=context.getElementsByTagName("*"); for(var i=0;i<e.length;i++){ if(e[i].className.match(patter)){ arr.push(e[i]); }; }; return arr; }; function YY(){ //存放节点的数组 this.elements=[]; //获取id this.getId=function(name){ this.elements.push(document.getElementById(name)); return this; }; //获取标签 this.getTag=function(tagname,context){ context=context||document; var eles=context.getElementsByTagName(tagname); for(var i=0;i<eles.length;i++){ this.elements.push(eles[i]); }; return this; }; //获取class this.getClass=function(name,context){ context=context||document; var eles; if(document.getElementsByClassName){ eles=context.getElementsByClassName(name); }else{ eles=getClassName(name,context); }; for(var i=0;i<eles.length;i++){ this.elements.push(eles[i]); }; return this; }; }; YY.prototype={ css:function(attr,val){ for(var i=0;i<this.elements.length;i++){ this.elements[i].style[attr]=val; }; return this; }, size:function(){ return this.elements.length; } }; var y=new YY(); $().getClass("dd",document.body).css("backgroundColor","red");