1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | <script type= "text/javascript" > function getElementsByClassName(className, parentElement){ if ( typeof parentElement == 'string' ){ parentElement = document.getElementById(parentElement); } else if ( typeof parentElement != 'object' || typeof parentElement.tagName != 'string' ){ parentElement = document.body; } var elems = parentElement.getElementsByTagName( "*" ); var result=[]; for (i=0; j=elems[i]; i++) { if (( " " +j.className+ " " ).indexOf( " " +className+ " " )!=-1) { result.push(j); } } return result; } function test() { var divs1 = getElementsByClassName( 'myclass' ); var divs2 = getElementsByClassName( 'myclass' , 'parent' ); var divs3 = getElementsByClassName( 'myclass' ,document.getElementById( 'parent' )); alert(divs1[0].innerText); alert(divs2[1].innerText); alert(divs3[2].innerText); } </script> <a href= "javascript:test();" >Click me</a> <div id= "parent" > <div class= "myclass" >1</div> <div class= "myclass" >2</div> <div class= "myclass" >3</div> </div> |
自定義getElementsByClassName函式,
可掃描指定id內之所有class名稱並以陣列儲存。
沒有留言:
張貼留言