//模仿jquery选择器样式,只需要写元素名或css类及id都可以选择到元素
<html><head><meta http-equiv="Content-Type:text/html;charset=utf=8"/><link rel="shortcut icon" href="#"/><title>封装选择器</title></head><style type="text/css">.context {color:black;font-size: 16px;width: 300px;height: 300px;}.div{border: 1px solid blue;}</style><body><div class="context div" >这是文本内容<ul><li class="listyle"><input type="text" name="user" value=""/></li><li class="listyle"><input type="password" name="pwd" value=""/></li><li class="listyle"><input type="password" name="pwd1" value=""/></li></ul></div><script type="text/javascript">Function.prototype.addMethods=function(name,fn){this.prototype[name]=fn;}function selectEle(selector){var selector=this.trim(selector);this.elements=[];var node;if(selector.indexOf(' ')!==-1){node=this.getClass(selector)[0];if(node){this.elements.push(node);}else if(node=this.getTagName(selector)){if(node.length>1){for(var i=0;i<node.length;i++){this.elements.push(node[i]);}}}else{throw "请输入正确的选择符";}}else if(selector.indexOf('[')!==-1){var selector=selector.slice(1,-1);node=this.getAttr(selector);//console.log(this.getAttr(selector));if(node){this.elements.push(node);}else{alert("请输入正确的选择符");}}else{if(/^[#|.]/.test(selector)){node=this.getCss(selector);if(node){this.elements.push(node);}else{alert("请输入正确的选择符");}}else{node=this.getTagName(selector);if(node.length==1){this.elements.push(node[0]);}else if(node.length>1){for(var i=0;i<node.length;i++){this.elements.push(node[i]);}}else{alert('请输入正确的选择符');}} }return this.elements;}selectEle.addMethods('getClass',function(selector){return document.getElementsByClassName(selector);});selectEle.addMethods('getCss',function(selector){try{return document.querySelector(selector);}catch(err){alert(err);}});selectEle.addMethods('getTagName',function(selector){try{return document.querySelectorAll(selector);}catch(err){alert(err);}});selectEle.addMethods('getAttr',function(selector){try{var tag=document.body.getElementsByTagName('*');var ele=[];if(selector.indexOf('=')==-1){for(var i=0;i<tag.length;i++){if(tag[i].getAttribute(selector)!=undefined && tag[i].tagName !="SCRIPT"){ele.push(tag[i]);}}}else{var selector=selector.split('=');for(var i=0;i<tag.length;i++){var att=tag[i].getAttribute(selector[0]);//console.log(att);if(att && att!=="text/javascript" && att!=="text/css"){if(att.toString().toLocaleLowerCase()===selector[1].toString().toLocaleLowerCase()){ele.push(tag[i]);}}}}return ele;}catch(err){alert(err);}});//只是为测试IE7/8写的临时兼容去空白函数selectEle.addMethods('trim',function(str){return str.replace(/^\s\s*/,'').replace(/\s\s*$/,'');});var $=function(args){return new selectEle(args);}console.log($('li'));</script> </body>
</html>