• getElementByClassName封装函数用法


    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
            "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <head>
        <title>getElementByClassName封装用法</title>
        <script type="text/javascript">
            function $(node){
                node=typeof  node=="string"?document.getElementById(node):node;
                return node;
            }
            function getClassName(str,root,tag){
                if(root){
                    root=typeof  root=="string"?document.getElementById(root):root;
                }else{
                    root=document.body;
                }
                tag=tag||"*";
                var els=root.getElementsByTagName(tag),arr=[];
                for(var i= 0,n=els.length;i<n;i++){
                    for(var j= 0,k=els[i].className.split(" "),l= k.length;j<l;j++){
                        if(k[j]==str){
                            arr.push(els[i]);
                            break;
                        }
                    }
                }
                return arr;
    
            }
    window.onload=function(){
        var a=getClassName("a");
        var b=getClassName("b",null,"strong");
        var c=$("box");
        var d=getClassName("b",c);
        for(var i=0;i< a.length;i++){
            a[i].onclick=function(){
                alert(this.innerHTML);
            }
        }
        //alert(a.length);
        //alert(b.length);
        //alert(d.innerHTML);
       alert(d.length);
    }
        </script>
    </head>
    
    <body>
    <span class="a">aa</span>
    <span class="a">aa2</span>
    <p class="a">aaa333</p>
    <strong class="b">bbbb</strong>
    
    <div id="box"><strong class="b">sdfdsf</strong></div>
    </body>
    </html>
    

    getClassName函数接收三个参数,其中第一个参数是必选的,后面两个参数可选。第一个参数是class名,第二个参数是父容器,缺省为body节点,第三个参数为DOM节点的标签名

  • 相关阅读:
    51Nod
    [HDU-5172] 单点查询线段树
    HihoCoder
    CodeForces
    计蒜客-T1271 完美K倍子数组
    [CodeForces-629A 用阶乘会爆掉
    计蒜客-A1139 dfs
    Codeforces Global Round 7 D2. Prefix-Suffix Palindrome (Hard version)(Manacher算法+输出回文字符串)
    HDU
    操作系统习题——虚地址转换为内存地址计算
  • 原文地址:https://www.cnblogs.com/hxh-hua/p/3202137.html
Copyright © 2020-2023  润新知