2008/01/01

[教學]HTML文件的階層架構 parentElement,children,contain

parentElement() 顯示比myP大一層的標籤
children()    顯示再往下一層找
contains():           檢查是否有子標籤(傳回true or flase)


source:


<html>
<head>
<title>存取父元素和子元素</title>
<script language="JavaScript">
function showParentTag(){
   alert(myP.parentElement.tagName);
}
function showChildsTag(){
   var strTags = "";
   for (var i=0; i<myP.children.length; i++){
      strTags += myP.children.item(i).tagName + " ";
   }
   alert(strTags);
}
function checkChild(){
   var objEle = document.all("myP").children.item(1);
   if (document.all("myP").contains(objEle))
      alert("myP有子元素" + objEle.tagName);
   else
      alert("myP沒有子元素" + objEle.tagName);
}
</script>
</head>
<body id="myBody">
<h2 id="myH2">存取父元素和子元素</h2>
<hr>
<p id="myP">存取<b><i>HTML</i></b>文件的<b>父元素</b>和<i>子元素</i></p>
<form>
<input type="button" onclick="showParentTag()" value="取得父元素">
<input type="button" onclick="showChildsTag()" value="顯示子元素">
<input type="button" onclick="checkChild()" value="檢查是否有子元素">
</form>
</body>
</html>


沒有留言: