簡體   English   中英

為什么不能通過document.getElementById(“ node's_id”)。child選擇子節點?

[英]Why can't I select nodes child by document.getElementById(“node's_id”).child?

假設我有一個簡單的html代碼,將父div和子span元素設置為:

<div id="my_div"><span> Nothin' but the G thang </span></div>

據說html DOM中的每個元素都是一個對象。 因此,我們可以選擇子對象作為parent.child 例如window.documentwindow.document.bodywindow.document.head等,那么我的問題是為什么document.getElementById("my_div").span返回未定義?

同樣, window.document.body可以,但是在window.document.body.div之后,我不能再下一層了。

. dot-notation ),您正在嘗試訪問document.getElementById返回的objectNode/Element )的span屬性。 由於沒有與返回的對象關聯的span屬性,因此document.getElementById("my_div").span將是undefined

使用document.querySelector返回與指定組匹配的 document.querySelector 中的第一個元素(使用文檔標記中的第一個元素,通過深度優先順序遍歷文檔的節點|通過子節點數量的順序遍歷順序節點)選擇器

 console.log(document.querySelector('#my_div span')); 
 <div id="my_div"><span> Nothin' but the G thang </span> </div> 

Node.chilren ,它是只讀屬性,它返回Node的子元素的實時HTMLCollection。

 console.log(document.getElementById('my_div').children[0]); 
 <div id="my_div"><span> Nothin' but the G thang </span> </div> 

您可以選擇像這樣的跨度

 var span = document.getElementById("my_div").querySelector('span'); console.log(span); 
 <div id="my_div"><span> Nothin' but the G thang </span> </div> 

或者您也可以使用firstChild

 var span = document.getElementById("my_div").firstChild; console.log(span); 
 <div id="my_div"><span>Nothin' but the G thang </span></div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM