[英]Why can't I select nodes child by document.getElementById(“node's_id”).child?
Suppose I have a simple html code sonsisiting a parent div
and child span
element as: 假设我有一个简单的html代码,将父
div
和子span
元素设置为:
<div id="my_div"><span> Nothin' but the G thang </span></div>
It is said that every element in html DOM is an object. 据说html DOM中的每个元素都是一个对象。 So we can select child objects as
parent.child
. 因此,我们可以选择子对象作为
parent.child
。 Eg window.document
, window.document.body
, window.document.head
etc then my question is why does document.getElementById("my_div").span
return undefined? 例如
window.document
, window.document.body
, window.document.head
等,那么我的问题是为什么document.getElementById("my_div").span
返回未定义?
Similarly window.document.body
works but I can't go one level down after that with window.document.body.div
. 同样,
window.document.body
可以,但是在window.document.body.div
之后,我不能再下一层了。
With .
用
.
( dot-notation
), you are trying to access the span
property of the object
( Node/Element
) returned by document.getElementById
. (
dot-notation
),您正在尝试访问document.getElementById
返回的object
( Node/Element
)的span
属性。 As there is no span
property associated with returned object, document.getElementById("my_div").span
will be undefined
由于没有与返回的对象关联的
span
属性,因此document.getElementById("my_div").span
将是undefined
Use document.querySelector
, Returns the first element within the document (using depth-first pre-order traversal of the document's nodes|by first element in document markup and iterating through sequential nodes by order of amount of child nodes) that matches the specified group of selectors 使用
document.querySelector
, 返回与指定组匹配的 document.querySelector
中的第一个元素(使用文档标记中的第一个元素,通过深度优先顺序遍历文档的节点|通过子节点数量的顺序遍历顺序节点)选择器
console.log(document.querySelector('#my_div span'));
<div id="my_div"><span> Nothin' but the G thang </span> </div>
Or Node.chilren
, read-only property that returns a live HTMLCollection of the child elements of Node. 或
Node.chilren
,它是只读属性,它返回Node的子元素的实时HTMLCollection。
console.log(document.getElementById('my_div').children[0]);
<div id="my_div"><span> Nothin' but the G thang </span> </div>
You can select span like this 您可以选择像这样的跨度
var span = document.getElementById("my_div").querySelector('span'); console.log(span);
<div id="my_div"><span> Nothin' but the G thang </span> </div>
Or in your case you can also use firstChild
或者您也可以使用
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.