看過一篇文章,其中講到用AJAX來操作DOM結點,其實自己也不是很明白,他提供了源碼的一個執行個體,可弄下來怎麼都不對,研究了半天最後修改出個能用的,給大家看看,呵呵,很簡單,捕獲頭兩級HTML結點並刪除一個IMAGE結點.
<html>
<head>
<title>JavaScript and the DOM</title>
<script language="JavaScript">...
function test() ...{
var myDocument = document;
var htmlElement = myDocument.documentElement;
alert("The root element of the page is " + htmlElement.nodeName);
var headElement = htmlElement.getElementsByTagName("head")[0];
if (headElement != null) ...{
alert("We found the head element, named " + headElement.nodeName);
var titleElement = headElement.getElementsByTagName("title")[0];
if (titleElement != null) ...{
var titleText = titleElement.firstChild;
//alert("The page title is " + titleText.nodeName);
}
var bodyElement = headElement.nextSibling;
while (bodyElement.nodeName.toLowerCase() != "body") ...{
bodyElement = bodyElement.nextSibling;
}
if (bodyElement.hasChildNodes()) ...{
for (i=0; i<bodyElement.childNodes.length; i++) ...{
var currentNode = bodyElement.childNodes[i];
if (currentNode.nodeName.toLowerCase() == "img")
...{
bodyElement.removeChild(currentNode);
}
}
}
}
}
</script>
</head>
<body>
<p>JavaScript and DOM are a perfect match.
You can read more in <i>Head Rush Ajax</i>.</p>
<img src="http://www.headfirstlabs.com/Images/hraj_cover-150.jpg" />
<input type="button" value="Test me!" onClick="test();" />
</body>
</html>