<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<ul>
<li>列表项01</li>
<li>列表项02</li>
<li>列表项03</li>
<li>列表项04</li>
<li>列表项05</li>
</ul>
</body>
<script>
//childNodes() 获取到父节点下的所有子节点
//页面中空白字符也是一个文本节点(例如回车)
var child = document.childNodes[1].childNodes[2]
console.log(child)
//children() 只获取元素节点
var body = document.children[0].children.item(1)
console.log(body)
//firstElementChild() 第一个子元素
body.firstElementChild.firstElementChild.style.background = 'pink'
//lastElementChild() 最后一个子元素
body.firstElementChild.lastElementChild.style.background = 'yellow'
//childElementCount() 获取子元素的数量
console.log(body.firstElementChild.childElementCount)
//nextElementSibling() 下一个兄弟元素
var li = document.getElementsByTagName('li').item(2)
li.nextElementSibling.style.background = 'red'
li.previousElementSibling.style.background = 'blue'
//parentElement() 父节点
li.parentElement.style.background = 'lightblue'
//parentNode() 父节点
li.parentNode.parentNode.style.background = 'gray'
</script>
</html>
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!