JavaScript 中特定節點的第一個和最後一個子節點?
在本文中,我們將學習 JavaScript 中特定節點的第一個和最後一個子節點,並附帶合適的示例。
要獲取特定節點的第一個和最後一個子節點,可以使用名為 firstChild、lastChild、firstElementChild 和 lastElementChild 的現有屬性。
firstChild 和 firstElementChild 屬性之間的區別在於,與 firstElementChild 相比,firstChild 將 HTML 元素中包含的文字和註釋都視為子節點。firstChild 還會考慮文字中的空格。lastChild 和 lastElementChild 也是如此。
獲取列表的第一個子節點
獲取列表第一個子節點的語法如下:
Node.firstChild; Or Node.firstElementChild;
其中,Node 可以是任何 HTML 元素,可以使用 id 名稱或類名訪問。返回特定節點的第一個子節點。
示例 1
這是一個使用firstChild 和firstElementChild 屬性在 JavaScript 中獲取特定節點的第一個和最後一個子節點的程式。說明了 firstChild 和firstElementChild 之間的區別。
在 id 為“car-list”的 ul 列表中,如果我們在第一個元素之前放置註釋,並在每個列表項之間放置空格,那麼當我們使用 firstChild 屬性訪問第一個子節點時,它將返回未定義。因此,在使用firstChild 屬性時避免使用空格,並且始終優先使用firstElementChild。lastChild 和 lastElementChild 也是如此。
<!DOCTYPE html> <html> <head> <title>A program to get the first child node of a specific node in JavaScript</title> </head> <body style="text-align: center ;"> <p> A program to get the first and last child node of a specific node in JavaScript using firstChild and firstElementChild property.</p> <ul id="car-list"> <li>BMW</li> <li>AUDI</li> <li>RANGE ROVER</li> <li>ROLLS ROYCE</li>//These are the top branded cars </ul> <ul id="top-selling-mobiles"> //Top selling mobiles <li>iPhone</li> <li>Samsung</li> <li>One plus</li> </ul> <p id="first-last"></p> <script> let first_child = document.getElementById('car-list').firstChild.innerHTML; let first_element_child = document.getElementById('top-selling-mobiles').firstElementChild.innerHTML; document.getElementById('first-last').innerHTML = 'First child for the list "car-list" : '+first_child + '<br/>' + 'First Element child for the list "top-selling mobile" : '+first_element_child; </script> </body> </html>
執行上述程式碼後,將生成以下輸出。
獲取列表的最後一個子節點
獲取列表最後一個子節點的語法如下:
Node.lastChild; Or Node.lastElementChild;
其中,Node 可以是任何 HTML 元素,可以使用 id 名稱或類名訪問。返回特定節點的最後一個子節點。
示例 2
這是一個使用lastChild 和lastElementChild 屬性在 JavaScript 中獲取特定節點的第一個和最後一個子節點的程式。說明了lastChild 和lastElementChild 之間的區別。
<!DOCTYPE html> <html> <head> <title>A program to get the first child node of a specific node in JavaScript</title> </head> <body style="text-align: center ;"> <p> A program to get the first and last child node of a specific node in JavaScript using lastChild and lastElementChild property.</p> <ul id="car-list"> //Top Branded Cars<li>BMW</li> <li>AUDI</li> <li>RANGE ROVER</li> <li>ROLLS ROYCE</li> </ul> <ul id="top-selling-mobiles"> //Top selling mobiles <li>iPhone</li> <li>Samsung</li> <li>One plus</li> </ul> <p id="last"></p> <script> let last_child = document.getElementById('car-list').lastChild.innerHTML; let last_element_child = document.getElementById('top-selling-mobiles').lastElementChild.innerHTML; document.getElementById('last').innerHTML = 'Last child for the list "car-list" : '+last_child + '<br/>' + 'Last Element child for the list "top-selling mobile" : '+last_element_child; </script> </body> </html>
執行上述程式碼後,將生成以下輸出。