<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名稱並以陣列儲存。
沒有留言:
張貼留言