<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Document</title>
<style>
#father{
width:300px;
height:300px;
margin:100px auto;
background-color: gray;
}
#father div{
width:300px;
height:50px;
background-color: blue;
margin:10px 0;
}
</style>
<script>
window.onload=function()
{
var kid=document.getElementById("kid");
//父节点
var father=kid.parentNode;
father.style.backgroundColor="pink";
//下一个兄弟节点
var brother=kid.nextElementSibling||kid.nextSibling; //下一个兄弟节点,兼容性写法,正常浏览器要写在前面
brother.style.backgroundColor="pink";
//上一个兄弟节点
var kid2=document.getElementById("kid2");
var brothershang=kid2.previousElementSibling||kid2.previousSibling;
brothershang.style.backgroundColor="pink";
//子节点,第一个孩子
var father=document.getElementById("father");
var kid1=father.firstElementChild||father.firstChild;
kid1.style.backgroundColor="green";
//子节点,最后一个孩子
var kidlast=father.lastElementChild||father.lastChild;
kidlast.style.backgroundColor="green";
//孩子节点,所有的孩子
var kidall=father.children; //children常用,childNodes不常用
for(var i=0;i<kidall.length;i++)
{
if(kidall[i].nodeType==1) //因为换行也是节点,所有需要利用nodeType==1,获取元素节点,改变所有孩子的背景颜色,否则换行节点没有背景颜色会报错
{
kidall[i].style.backgroundColor="orange";
}
}
}
</script>
</head>
<body>
<div id="father">
<div id="kid"></div>
<div id="kid2"></div>
<div></div>
<div></div>
<div></div>
</div>
</body>
</html>