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節點的標籤名javascript

相關文章
相關標籤/搜索