一、節點之間的關系
- (1)獲取父節點
- (2)上一個兄弟節點
- (3)下一個兄弟節點
- (4)獲取標簽中的第一個子節點
- (5)獲取標簽中的最后一個子節點
- (6)獲取元素的節點
- (7)獲取任意兄弟的節點
- 節點包括:標簽、屬性、文本、注釋等
- 直接上代碼
<style>
#box{
width:200px;
height:200px;
background-color: red;
}
</style>
</head>
<body>
<div id="box">
<button class="btn">按鈕</button>
<span id="span">
<a href=https://www.cnblogs.com/ruigege0000/p/"#">一個鏈接
我是段落標簽
哈哈哈
<script>
window.onload = function (ev) {
var a = document.getElementsByTagName('a')[0];
console.log(a.parentNode);//獲取父節點
console.log(a.parentElement);//也是用來獲取父節點,但還有點區別,后面再說
//獲取兄弟節點
var span = document.getElementById("span");
//下一個節點
var nextEle = span.nextSibling;//在JS中也會把空格和換行當成一個標簽
var nextEle2 = span.nextElementSibling || span.nextSibling;//這樣做一個判斷,拿來的元素的節點而不是換行或者空格
var preEle = span.previousElementSibling || span.previousSibling;
console.log(nextEle);
console.log(nextEle2);
console.log(preEle);
console.log("-------------------");
var box = document.getElementById("box");
//獲取第一個子節點
console.log(box.firstElementChild || box.firstChild);
//獲取最后一個節點
console.log(box.lastElementChild || box.lastChild);
//獲取所有的節點
console.log(box.childNodes);
//獲取所有的元素節點(也就是非換行空格的節點)
console.log(box.children);
}
</script>
</body>