getElementByClass
資料來源: webmasterworld、mixfog
Javascript 中 的 getElementById 十分常用,但在標準的頁面中,一個id只能出現一次,如果我想同時控制多個元素,例如點一個鏈接, 讓多個層隱藏,該怎麼做?
用 class,當然,同一個class是可以允許在頁面中重複出現的,那麼有沒有getElementByClass呢?
沒有, 但是可以解決:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <script language="javascript"> //Create an array var allPageTags = new Array(); function hideDivWithClasses(theClass) { //Populate the array with all the page tags var allPageTags=document.getElementsByTagName("div"); //Cycle through the tags using a for loop for (i=0; i < allPageTags.length;) { //Pick out the tags with our class name if (allPageTags[i].className==theClass) { //Manipulate this in whatever way you want allPageTags[i].style.display='none'; i++; } } } </script> |