javaScriptの中でgetElementByClass Nameの実現

3633 ワード

<style>
	body{
		margin:0px;
		padding:0px;
		}
	#div1{
		width:300px;
		height:200px;
		background:#CC3;
		margin:30px auto 0px 10px;
		position:relative;
		}
	#div2{
		width:300px;
		height:200px;
		background:#096;
		position:absolute;
		left:310px;
	}
	#div11{
		margin-left:10px;
		}	
</style>

</head>
<body>
	<div id='div1' class='div1'>
    	xxxxxx
        <div id='div11' class='div1'>fasdfa</div>
    </div>
	<div id='div2' class='div1'>
    
    </div>
    <div id='div3' class='div1'  style="width:200px">
    	<div id='div31' class='div1'></div>
    </div>

</body>
 
//     chrome  40.0.2214.115 
//getElementByClassName     
//               ,           
window.onload=function(){
		//            
		console.info(document.getElementsByClassName('div1'));
		console.info(document.getElementById('div1').getElementsByClassName('div1'));
		var oNodes=document.getElementsByTagName('*');
		console.info(oNodes);//HTMLCollection[14]
		for(var i=0;i<oNodes.length;i++){
				console.info(oNodes[i]+' '+oNodes[i].className+' '+i);
				if(oNodes[i].className){
						console.info('calssName:  '+oNodes[i].className);
					}else{
							console.info('calssName:    ');
						}
				
			}
			
			
		//    
		//  
		// getElementsByTagName('*'),            
		//    ,            ,         
		
		//        
		var temp=new RegExp("^|\\s"+"fsdfsa"+"\\s|$","ig")
		console.info(temp);
		console.info(temp.test(  'fSdfsa'  ));
		//         ,   Object    ,       
		function getFilter(className){
				//        
				if(this.getElementsByClassName){
						this.getElementsByClassName(className);
					}else{	
							var ret=[];
							var oNodes=this.getElementsByTagName('*');
							for(var i=0;i<oNodes.length;i++){
									if(new RegExp("^|\\s"+className+"\\s|$","ig").test(oNodes[i].className)){
											ret.push(oNodes[i]);
										}
								}
							return ret;
						}
				
			}
		//      
		
		/*function getFilter1(className){
				var ret=[];
				var oNodes=this.getElementsByTagName('*');
				for(var i=0;i<oNodes.length;i++){
						if(new RegExp("^|\\s"+className+"\\s|$","ig").test(oNodes[i].className)){
								ret.push(oNodes[i]);
							}
					}
				return ret;
			}*/
		//     getElementsByTagName      
		 Object.prototype.getFilter1=function(className){
				var ret=[];
				var oNodes=this.getElementsByTagName('*');
				for(var i=0;i<oNodes.length;i++){
						if(new RegExp("^|\\s"+className+"\\s|$","ig").test(oNodes[i].className)){
								ret.push(oNodes[i]);
							}
					}
				return ret;
			};
		 console.info(document.getElementById('div1').getFilter1('div1'));//     
	};
 //これで終わりです