jquery - 使用 .text() 仅检索未嵌套在子标签中的文本

标签 jquery text tags

如果我有这样的 html:

<li id="listItem">
    This is some text
    <span id="firstSpan">First span text</span>
    <span id="secondSpan">Second span text</span>
</li>

我正在尝试使用 .text() 来检索字符串“This is some text”,但如果我说 $('#list-item') .text(),我得到“这是一些 textFirst span textSecond span 文本”。

有没有办法只获取(并可能通过 .text("") 等方式删除)标签内的自由文本,而不是其子标签内的文本?

HTML 不是我写的,所以这是我必须处理的。我知道在编写 html 时将文本包装在标签中会很简单,但同样,html 是预先编写的。

最佳答案

我喜欢这个基于 clone() 方法的可重用实现here仅获取父元素内的文本。

提供代码以方便引用:

$("#foo")
    .clone()    //clone the element
    .children() //select all the children
    .remove()   //remove all the children
    .end()  //again go back to selected element
    .text();

关于jquery - 使用 .text() 仅检索未嵌套在子标签中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39959005/

相关文章:

javascript - 加载完所有内容后发出警报?

javascript - 如何避免没有 src 的 iframe 读取其父 HTML?

Python翻译器,如何只替换一个单词

android - 可以在 Google Analytics 中为 Android 应用创建虚拟网页浏览吗?

php - php mysql 对两列进行排序

javascript - 在 Firebug/Chrome 中获取从一个断点到另一个断点的 Javascript 或 jQuery 堆栈跟踪?

javascript - 求客户端方格的坐标

python - 如何在文本文件中写入多个变量 - Python?

linux - 标记两个文件中的差异

java - Java-在getLegalMoves()中找不到符号