<html> <head> <title>擷取HTML檔案的指定元素</title> <script language="JavaScript"> function getElement1(){ alert(document.all("myH2").tagName); } function getElement2(){ alert(myH2.tagName); } function showTags(){ alert(document.all.tags("P").length); } function showItems(){ var strTags = ""; for (var i=0; i<document.all["myTag"].length; i++){ objEle = document.all("myTag").item(i); strTags += objEle.tagName + " "; } alert(strTags); } </script> </head> <body id="myBody"> <h2 id="myH2">擷取HTML檔案的指定元素</h2> <hr> <p id="myTag">擷取<b id="myTag">HTML</b>檔案的元素Body</p> <p id="myTag">擷取<b>HTML</b>檔案的元素H2</p> <h3 id="myTag">擷取<b>HTML</b>檔案的元素P</h3> <form> <input type="button" onclick="getElement1()" value="擷取指定的元素"> <input type="button" onclick="getElement2()" value="擷取指定的元素"> <input type="button" onclick="showTags()" value="多少個P元素"> <input type="button" onclick="showItems()" value="顯示myTag元素"> </form> </body> </html>
[Ctrl+A 全選 注:如需引入外部Js需重新整理才能執行]