[英]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.document
, window.document.body
, window.document.head
等,那么我的問題是為什么document.getElementById("my_div").span
返回未定義?
同樣, window.document.body
可以,但是在window.document.body.div
之后,我不能再下一層了。
用.
( dot-notation
),您正在嘗試訪問document.getElementById
返回的object
( Node/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.