使用.text()仅检索未嵌套在子标记中的文本 [英] Using .text() to retrieve only text not nested in child tags

查看:117
本文介绍了使用.text()仅检索未嵌套在子标记中的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这样的html:

If I have html like this:

<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(),则会收到"This is sometextFirst span textSecond span text".

I'm trying to use .text() to retrieve just the string "This is some text", but if I were to say $('#list-item').text(), I get "This is some textFirst span textSecond span text".

是否有办法仅获取(可能通过.text("")之类的)标签中的自由文本,而不是其子标签中的文本?

Is there a way to get (and possibly remove, via something like .text("")) just the free text within a tag, and not the text within its child tags?

HTML不是我编写的,因此这是我必须使用的.我知道在编写html时只将文本包装在标签中会很简单,但是html是预先编写的.

The HTML was not written by me, so this is what I have to work with. I know that it would be simple to just wrap the text in tags when writing the html, but again, the html is pre-written.

推荐答案

我喜欢这种基于clone()方法的可重用实现,该方法基于

I liked this reusable implementation based on the clone() method found here to get only the text inside the parent element.

提供的代码便于参考:

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

这篇关于使用.text()仅检索未嵌套在子标记中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆