为什么我不能 select 节点由 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>
据说htmlDOM中的每个元素都是一个对象。所以我们可以 select 子对象作为 parent.child
。例如。 window.document
、window.document.body
、window.document.head
等那么我的问题是为什么 document.getElementById("my_div").span
return 未定义?
类似地,window.document.body
可以工作,但之后我无法再使用 window.document.body.div
下一级。
使用 .
(dot-notation
),您正在尝试访问返回的 object
(Node/Element
) 的 span
属性通过 document.getElementById
。由于没有 span
属性 与返回的对象相关联,因此 document.getElementById("my_div").span
将是 undefined
使用document.querySelector
,Returns文档中的第一个元素(使用文档节点的深度优先预序遍历|通过文档标记中的第一个元素迭代按子节点数量的顺序通过顺序节点)匹配指定的选择器组
console.log(document.querySelector('#my_div span'));
<div id="my_div"><span> Nothin' but the G thang </span>
</div>
或者Node.chilren
,只读属性即returns一个活的Node子元素HTMLCollection。
console.log(document.getElementById('my_div').children[0]);
<div id="my_div"><span> Nothin' but the G thang </span>
</div>
你可以select这样跨越
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>
假设我有一个简单的 html 代码将父 div
和子 span
元素设置为:
<div id="my_div"><span> Nothin' but the G thang </span></div>
据说htmlDOM中的每个元素都是一个对象。所以我们可以 select 子对象作为 parent.child
。例如。 window.document
、window.document.body
、window.document.head
等那么我的问题是为什么 document.getElementById("my_div").span
return 未定义?
类似地,window.document.body
可以工作,但之后我无法再使用 window.document.body.div
下一级。
使用 .
(dot-notation
),您正在尝试访问返回的 object
(Node/Element
) 的 span
属性通过 document.getElementById
。由于没有 span
属性 与返回的对象相关联,因此 document.getElementById("my_div").span
将是 undefined
使用document.querySelector
,Returns文档中的第一个元素(使用文档节点的深度优先预序遍历|通过文档标记中的第一个元素迭代按子节点数量的顺序通过顺序节点)匹配指定的选择器组
console.log(document.querySelector('#my_div span'));
<div id="my_div"><span> Nothin' but the G thang </span>
</div>
或者Node.chilren
,只读属性即returns一个活的Node子元素HTMLCollection。
console.log(document.getElementById('my_div').children[0]);
<div id="my_div"><span> Nothin' but the G thang </span>
</div>
你可以select这样跨越
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>