javascript - 选择带有 DOM 的 div 内容,但没有子元素

标签 javascript html dom

有 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 first Element 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/

相关文章:

javascript - 为部署在 tomcat 上的 react\spring 应用程序配置 url

javascript - 在 javascript 对象中引用另一个字段

javascript - 没有 HTTPS 的带有 Google Hangout API 的本地 Javascript 文件

javascript - IE8 表示 'Object doesn' t 支持 Date.now() 的此属性或方法

html - 如何检测浏览器中的目录选择功能?

html - 如何使用 z-index 将一个导航菜单堆叠在另一个导航菜单之上?

html - CSS | Navigationlinks 填充问题

jquery - 向 DOM 添加大量元素

python - 使用 xml.etree.ElementTree 在 Python 中进行简单的 dom 遍历

dom - 在 Prototype 中使用 $$ 是不是不好?