DOM初探
三种节点
- 元素节点
- 属性节点
- 文本节点
nodeValue属性
- node.nodeValue是获取属性节点对应属性的值
nodeType属性
+node. nodeType 是节点的类型,元素节点的nodeType = 1,属性节点的nodetype = 2, 文本节点的nodeType = 3。当节点不存在时nodeType= null
childNodes属性
- 获取节点的所有子节点,返回值为数组形式
firstChild 属性
- 获取第一个子节点,和node.childNodes[0]等价
lastChild属性
- 获取最后一个子节点,和node.childNodes[document.getElementByTagName(“li”).length-1]等价
最后通过代码来深入了解这几个属性的用法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Image gallery</title>
<style type="text/css">
body{
font-family: "Helvetica","Arial",sans-serif;
color: #333;
background-color: lightblue;
margin: 1em 10%;
}
h1{
color: #333;
background-color: transparent;
}
a{
color: #c60;
background-color: transparent;
font-weight: bold;
text-decoration: none;
}
ul{
padding: 0;
}
li{
float: left;
padding: 1em;
list-style: none;
}
</style>
<script type="text/javascript">
function showPic(whichPic) {
var placeHolder = document.getElementById('placeholder');
var source = whichPic.getAttribute('href');
placeHolder.setAttribute('src', source);
var text = whichPic.getAttribute('title');
var description = document.getElementById('description');
description.firstChild.nodeValue = text;
}
</script>
</head>
<body>
<h1>snapshots</h1>
<ul>
<li>
<a href="pictures/tree.png" onclick="showPic(this);return false" title="firework display">
Fireworks</a>
</li>
<li>
<a href="pictures/home.png" onclick="showPic(this);return false" title="coffee display">
Coffee</a>
</li>
<li>
<a href="pictures/timg.jpeg" onclick="showPic(this);return false" title="rose display">
Rose</a>
</li>
<li>
<a href="pictures/31_379_bp.jpg" onclick="showPic(this);return false" title="big ben display">
Big Ben</a>
</li>
</ul>
<img id="placeholder" src="pictures/state.jpg" alt="my image gallery"/>
<p id="description">choose an image</p>
</body>
</html>