use*_*782 1 javascript dom parent-child nodes
假设我有一个简单的 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),您正在尝试访问由 所返回的( )span的属性。由于没有与返回对象关联的属性,因此将objectNode/Elementdocument.getElementByIdspandocument.getElementById("my_div").spanundefined
使用document.querySelector,返回文档中与指定选择器组匹配的第一个元素(使用文档节点的深度优先前序遍历|按文档标记中的第一个元素,并按子节点数量的顺序迭代顺序节点)
console.log(document.querySelector('#my_div span'));Run Code Online (Sandbox Code Playgroud)
<div id="my_div"><span> Nothin' but the G thang </span>
</div>Run Code Online (Sandbox Code Playgroud)
或者Node.chilren,只读属性,返回 Node 子元素的实时 HTMLCollection。
console.log(document.getElementById('my_div').children[0]);Run Code Online (Sandbox Code Playgroud)
<div id="my_div"><span> Nothin' but the G thang </span>
</div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
880 次 |
| 最近记录: |