<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="common.js"></script>
</head>
<body>
<div id="dv">
<span>这是div中的第一个span标签</span>
<p>这是div中的第二个元素,第一个p标签</p>
<ul id="uu">
<li>乔峰</li>
<li>鹿茸</li>
<li id="three">段誉</li>
<li>卡卡西</li>
<li>雏田</li>
</ul>
</div>
<script>
var ulObj=my$("uu");
console.log(ulObj.parentNode);
console.log(ulObj.parentElement);
console.log(ulObj.childNodes);
console.log(ulObj.children);
console.log("==============================================");
console.log(ulObj.firstChild);
console.log(ulObj.firstElementChild);
console.log(ulObj.lastChild);
console.log(ulObj.lastElementChild);
console.log(my$("three").previousSibling);
console.log(my$("three").previousElementSibling);
console.log(my$("three").nextSibling);
console.log(my$("three").nextElementSibling);
</script>
<script>
</script>
</body>
</html>
节点的部分兼容代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="common.js"></script>
</head>
<body>
<ul id="uu">
<li>第一个</li>
<li>第二个</li>
<li>第三个</li>
<li>第四个</li>
<li>第五个</li>
</ul>
<script>
function getFirstElementChild(element) {
if(element.firstElementChild){
return element.firstElementChild;
}else{
var node=element.firstChild;
while(node&&node.nodeType!=1){
node=node.nextSibling;
}
return node;
}
}
function getLastElementChild(element) {
if(element.lastElementChild){
return element.lastElementChild;
}else{
var node=element.lastChild;
while(node&&node.nodeType!=1){
node=node.previousSibling;
}
return node;
}
}
</script>
</body>
</html>
点击按钮设置p标签中的背景颜色
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="common.js"></script>
<style>
div {
width: 300px;
height: 300px;
border: 1px solid red;
}
</style>
</head>
<body>
<!--点击按钮设置p标签中的背景颜色-->
<input type="button" value="变色" id="btn"/>
<div id="dv">
<span>这是span</span>
<p>这是p</p>
<span>这是span</span>
<p>这是p</p>
<span>这是span</span>
<p>这是p</p>
<span>这是span</span>
<a href="http://www.baidu.com">百度</a>
</div>
<script>
my$("btn").onclick=function () {
var obj=my$("dv").childNodes;
for(var i=0;i<obj.length;i++){
if(obj[i].nodeName=="P"&&obj[i].nodeType==1){
obj[i].style.backgroundColor="red";
}
}
};
</script>
</body>
</html>