有 HTML 代码:
<div id="parent">
<p>111111</p>
<div id="child">
<p>22222</p>
<div id="childer">
<p>33333</p>
</div>
</div>
</div>
我只想在 id=child 的 div 段落中选择“22222”。
但是当使用document.getElementById("child").textContent
时它返回“22222”和“33333”。
我不想使用 jQuery,有人可以帮助我吗?
谢谢
最佳答案
您可以使用querySelector()
,更多信息here .
The
Document
method querySelector() returns the firstElement
within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.
var value = document.querySelector('#child p').textContent;
console.log(value);
<div id="parent">
<p>111111</p>
<div id="child">
<p>22222</p>
<div id="childer">
<p>33333</p>
</div>
</div>
</div>
关于javascript - 选择带有 DOM 的 div 内容,但没有子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60744413/