获取所有子节点
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JS</title>
</head>
<body>
<div id="box">
<button class="btn">按钮</button>
<span id="span">
<a href="#">百度一下</a>
</span>
<p>我是段落</p>
</div>
<script type="text/javascript">
window.onload = function() {
var box = document.getElementById("box");
//获取第一个子节点
console.log(box.firstElementChild || box.firstChild);
//获取最后一个子节点
console.log(box.lastElementChild || box.lastChild);
// 获取所有子节点
var allNodeList = box.childNodes;
console.log(allNodeList);
var newList = [];
for (var i = 0; i < allNodeList.length; i++) {
var node = allNodeList[i];
if (node.nodeType === 1) { //判断类型
newList.push(node);
}
}
console.log(newList);
}
</script>
</body>
</html>
获取直接子节点
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JS</title>
</head>
<body>
<div id="box">
<button class="btn">按钮</button>
<span id="span">
<a href="#">百度一下</a>
</span>
<p>我是段落</p>
</div>
<script type="text/javascript">
window.onload = function() {
var box = document.getElementById("box");
//输出一级子节点
var nodeList = box.children;
console.log(nodeList);
}
</script>
</body>
</html>