访问文档中的所有元素
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>DOM Example</title>
<script type="text/JavaScript" src="exampleFindElements.js">
</script>
</head>
<body>
<h1>Heading</h1>
<p>Paragraph</p>
<h2>Subheading</h2>
<ul id="eventsList">
<li>List 1</li>
<li>List 2</li>
<li><a href="http://www.baidu.com">Linked List Item</a></li>
<li>List 4</li>
</ul>
<p>Paragraph</p>
<p>Paragraph</p>
</body>
</html>
exampleFindElements.js:
function findElements()
{
var listElements=document.getElementsByTagName('li');
var paragraphs=document.getElementsByTagName('p');
var msg='This document contains '+listElements.length+' list items '
msg+=' and '+paragraphs.length+' paragraphs.';
//alert(msg);
//Get the first paragraph
var firstpara=document.getElementsByTagName('p')[0];
//Get the second list item
var secondListItem=document.getElementsByTagName('li')[1];
//Get last list item
var lastListItem=listElements[listElements.length-1];
//Get son Item
var targetLink=document.getElementsByTagName('li')[2].getElementsByTagName('a')[0];
//Get by id
var events=document.getElementById('eventsList');
//Set the value of node
document.getElementsByTagName('p')[0].firstChild.nodeValue='Hello woorld!';
alert(firstpara);
alert(secondListItem);
alert(lastListItem);
alert(targetLink);
alert(events);
}
//Get all Chilren node
function myDOMinspector()
{
var DOMstring='';
if(!document.getElementById||!document.createTextNode){return;}
var demoList=document.getElementById('eventsList');
if(!demoList){return;}
if(demoList.hasChildNodes())
{
var ch=demoList.childNodes;
for(var i=0;i<ch.length;i++)
{
DOMstring+=ch[i].firstChild.nodeValue+'\n'+ch[i].nodeName+'\n';
}
alert(DOMstring);
}
}
window.onload=findElements;
window.onload=myDOMinspector;