Home  >  Article  >  Web Front-end  >  How to find elements in native JS (recommended)

How to find elements in native JS (recommended)

高洛峰
高洛峰Original
2016-12-05 17:22:37969browse

今天写了一个很简单、很粗暴的通过JS根据类来查找DOM元素。

为了降低它的粗暴等级(耗费性能)我给了三个等级。

首先性能最好的,适合FF,CH,IE8,通过querySelectorAll这个API。

其次是指定ID

最后只能全页面进行匹配class,不过比较节省的性能的是,在指定class名称的时候,同时传入HTML标签的类型,用于节省遍历的范围!

因为水平有限,目前也只能写成这种,真的好好奇JQ的选择器是怎么去匹配DOM的,如果有大神看到这篇文章,请不要吝啬施教。。。

下面贴代码:

function $(d,t){
     
    var c = null, // className 
      e = null, // element
      i = null; // id
 
    function type(p){
      /function.(\w*)\(\)/.test(p.constructor);
      return RegExp.$1.toLowerCase();
    }
 
    if(type(d) == 'string'){ 
 
      if(/^\.[a-z,A-Z,_]\w*$/.test(d)){ // 匹配class
        c = d;
      }else if(/^#[a-z,A-Z,_]\w*$/.test(d)){ // 匹配id
        i = d;
      }else if(/^[a-z,A-Z,_]+$/.test(d)){ // 匹配元素
        e = d;
      }else{
        return undefined;
      }
      if(document.querySelectorAll){ 
 
        if(c || e) return document.querySelectorAll(c || e);
        if(i) return document.querySelectorAll(i)[0];
 
      }else{
        if(c){
          var all = document.getElementsByTagName(t || '*'),
            cn = c.slice(1,c.length),
            reg = new RegExp('^'+cn+'\\b'), // 限定类名的起始,结束只要是相同字符结束即可。
            em = [];
            for(var i=0;i<all.length;i++){
              if(reg.test(all[i].className)){
                em.push(all[i])
              }
            }
            return em;
        }else if(e){
          return document.getElementsByTagName(e);
        }else if(i){
          return document.getElementById(i);
        }
      }
       
    }else{
      return undefined;
    }
 
  }

调用方式:

$(&#39;selector&#39;[,type])


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn