Home  >  Article  >  Web Front-end  >  Detailed introduction to Javascript encapsulation id, class and element selector sample code sharing

Detailed introduction to Javascript encapsulation id, class and element selector sample code sharing

黄舟
黄舟Original
2017-03-20 15:01:451686browse

这篇文章主要给大家介绍了Javascript封装id、class与元素选择器的方法,文中给出了详细的示例代码,对大家的理解和学习具有一定的参考价值,需要的朋友们下面来一起看看吧。

由于各个浏览器都支持的选择方法只有如下三种:

     1、document.getElementById()

     2、document.getElementsByName()

     3、document.getElementsByTagName()

所以在封装选择器的时候要考虑浏览器的兼容性。

示例代码如下:

<script>//封装id选择器
  function $(selector){
    var c=selector.substring(0,1);//获取第一个字符
    if(c=="#"){
      return document.getElementById(selector.substring(1,selector.length));//返回相应的元素
    }
  }
  
  
  //封装class选择器
  function $(selector){
    var className=selector.substring(1);//从索引为1的元素往后取
    //判断浏览器是否支持getElementsByClassName
    if(document.getElementsByClassName){
      return document.getElementsByClassName(className)
      //document.querySelectorAll(&#39;.cls&#39;)兼容性有问题
    }else{
      //document.getElementsByTagName(&#39;*&#39;)+正则表达式
      //\s空白字符 ^开始 $结束
      var reg=new RegExp(&#39;^|\\s&#39;+className+&#39;$|\\s&#39;);
      var elems=document.getElementsByTagName("*");//获取页面中所有元素
      var arr=[];//保存获取到的指定className的元素
      for(var i=0;i<elems.length;i++){
        if(reg.test(elems[i].className)){//如果和模式匹配上
          arr.push(elem[i]);
        }
      }
      return arr;
    }
  }
  
  //封装标签选择器  
  function $(element){
    return document.getElementsByTagName(element);
  }
 </script>

总结

The above is the detailed content of Detailed introduction to Javascript encapsulation id, class and element selector sample code sharing. For more information, please follow other related articles on the PHP Chinese website!

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