The Document Object Model
- The concept of nodes;
- Five very handly DOM methods:
getElementById
,getElementByTagName
,getElementsByClassName
,getAttribute
andsetAttribute
D is for document
HTML 就是 Document 的表现形式
Object of desire
各种各样的对象,比如
- window
- document
Dia M for model
标签树
Nodes
- Element nodes
- Text nodes
- Attribute nodes
举个例子
<p title="a gentle reminder">Don't forget to buy this stuff.</p>
Element nodes
是: <p></p>
Text nodes
是 Don't forget to buy this stuff.
Attribute nodes
是 title="a gentle reminder"
Getting Elements
<!DOCTYPE html>
<html lang="en">
<head>
<meta 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 class="sale">Cheese</li>
<li class="sale important">Milk</li>
</ul>
<script>
alert(typeof document.getElementById("purchases"));
</script>
</body>
</html>
- document.getElementById("purchases")
- document.getElementsByTagName("li")
- document.getElementsByClassName("sale")
Getting and Setting Attributes
getAttribute
var paras = document.getElementsByTagName("p");
for (var i=0; i < paras.length; i++ ) {
console.log(paras[i].getAttribute("title"));
}
setAttribute
var paras = document.getElementsByTagName("p");
for (var i=0; i< paras.length; i++) {
var title_text = paras[i].getAttribute("title");
if (title_text) {
paras[i].setAttribute("title","brand new title text");
console.log(paras[i].getAttribute("title"));
}
}
网友评论