<style> #box{ width:200px; height:200px; background-color: red; } </style> </head> <body> <div id="box"> <button class="btn">按鈕</button> <span id="span"> <a href="#">一個連接</a> </span> <p class="lk">我是段落標籤</p> <div>哈哈哈</div> </div> <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>
https://github.com/ruigege66/JavaScript/blob/master/DD28_1_GetAPI.html
https://www.cnblogs.com/ruigege0000/
https://blog.csdn.net/weixin_44630050?t=1