<JavaScript DOM 编程艺术>第三章的例子
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<style>
body {
color: white;
background-color: black;
}
p {
color: yellow;
font-family: "arial", sans-serif;
font-size: 1.2em;
}
.special {
font-style: italic;
}
h2.special {
text-transform: uppercase;
}
#purchases {
border: 1px solid white;
background-color: #333;
color: #ccc;
padding: 1em;
}
#purchases li {
font-weight: bold;
}
</style>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Shopping list</title>
</head>
<body>
<h1>What to buy</h1>
<p title="a gentle reminder">Don't forget to buy this stuff.</p>
<ul id="purchases">
<li>A tin of beans</li>
<li>Cheese</li>
<li>Milk</li>
</ul>
<p class="special">This paragraph has the special class</p>
<h2 class="special">So does this headline</h2>
<script>
var println = function(arg) {
if (arg)
document.write(arg);
document.write("<br />");
}
println("getElementById():");
println("id purchases: " + document.getElementById("purchases"));
println("innerText: " + document.getElementById("purchases").innerText);
println();
println("getElementsByTagName():")
li_items = document.getElementsByTagName("li");
println("tag li: " + li_items);
println("length: " + li_items.length);
for (var i = 0; i < li_items.length; i++) {
println(i + ": " + document.getElementsByTagName("li")[i].innerText);
}
println();
println("with \"*\" :");
println("all tags: " + document.getElementsByTagName("*").length);
println();
println("combine ById and ByTagName - get tags in a id: ")
var shopping = document.getElementById("purchases");
var items = shopping.getElementsByTagName("*");
println("tag \"*\" in id \"purchases\": " + items.length);
println();
println("object.getAttribute(attribute) - get title attribute of the objects which tags are p");
var tags_p = document.getElementsByTagName("p");
for (var i = 0; i < tags_p.length; i++) {
println(tags_p[i].getAttribute("title"));
}
println();
println("object.setAttribute(attribute, value) - set title attribute of the object which id is purchases");
var shopping = document.getElementById("purchases");
shopping.setAttribute("title", "a list of goods");
println(shopping.getAttribute("title"));
</script>
</body>
</html>