JavaScript-獲取當前元素的相關元素或節點--方法總結

 

1.獲取當前元素中的第一個子節點測試

document.getElementById("uu").firstChild

 


2.獲取當前元素中的第一個子元素spa

document.getElementById("uu").firstElementChild

 


3.獲取當前元素中的最後一個子節點code

document.getElementById("uu").lastChild

 


4.獲取當前元素中的最後一個子元素blog

document.getElementById("uu").lastElementChild

 


5.獲取當前元素的父級節點three

document.getElementById("uu").parentNode

 


6.獲取當前元素的父級子元素ip

document.getElementById("uu").parentElement

 


7.獲取當前元素的子節點get

document.getElementById("uu").childNodes

 


8.獲取當前元素的子元素io

document.getElementById("uu").children

 


9.獲取當前元素的前一個兄弟節點console

document.getElementById("three").previousSibling

 


10.獲取當前元素的前一個兄弟元素ast

document.getElementById("three").previousElementSibling

 


11.獲取當前元素的後一個兄弟節點

document.getElementById("three").nextSibling

 


12.獲取當前元素的後一個兄弟元素

document.getElementById("three").nextElementSibling

 

 

測試所用代碼:

<body>
<div id="dv">
    <p>層中的第一個p標籤</p>哈哈哈
    <span>層中的第二個標籤==span</span>
    <ul id="uu">嘎嘎
        <li>火箭</li>
        <li>熱火</li>
        <li id="three">湖人</li>
        <li>小牛</li>
        <li>公牛</li>嘿嘿
    </ul>
</div>
<script>
    function my$(id) {
      return document.getElementById(id);
    }
</script>
<script>
    //獲取當前元素中的第一個子節點
    console.log(my$("uu").firstChild);
    //獲取當前元素中的第一個子元素
    console.log(my$("uu").firstElementChild);
    //獲取當前元素中的最後一個子節點
    console.log(my$("uu").lastChild);
    //獲取當前元素中的最後一個子元素
    console.log(my$("uu").lastElementChild);
    //獲取當前元素的父級節點
    console.log(my$("uu").parentNode);
    //獲取當前元素的父級子元素
    console.log(my$("uu").parentElement);
    //獲取當前元素的子節點
    console.log(my$("uu").childNodes);
    //獲取當前元素的子元素
    console.log(my$("uu").children);
    //獲取當前元素的前一個兄弟節點
    console.log(my$("three").previousSibling);
    //獲取當前元素的前一個兄弟元素
    console.log(my$("three").previousElementSibling);
    //獲取當前元素的後一個兄弟節點
    console.log(my$("three").nextSibling);
    //獲取當前元素的後一個兄弟元素
    console.log(my$("three").nextElementSibling);
</script>
</body>
相關文章
相關標籤/搜索