gpt4 book ai didi

javascript - 为什么我无法通过 document.getElementById ("node' s_id").child 选择子节点?

转载 作者:行者123 更新时间:2023-11-28 13:17:09 24 4
gpt4 key购买 nike

假设我有一个简单的 html 代码 sonsisiting 父 div和 child 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),您正在尝试访问对象span属性(Node/Element) 由 document.getElementById 返回。由于没有与返回对象关联的 span 属性,document.getElementById("my_div").span 将为 undefined

使用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>

关于javascript - 为什么我无法通过 document.getElementById ("node' s_id").child 选择子节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36837918/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com