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

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

问题描述

如果我有这样的 html:

  • 这是一些文字<span id="firstSpan">第一个跨度文本</span><span id="secondSpan">第二个跨度文本</span>
  • 我正在尝试使用 .text() 来检索字符串This is some text",但如果我要说 $('#list-item').text(),我得到这是一些 textFirst span textSecond span text".

    有没有办法只获取(并可能通过诸如 .text("") 之类的东西来获取(并可能删除)标签中的自由文本,而不是其子标签中的文本?>

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

    解决方案

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

    提供代码以供参考:

    $("#foo").clone()//克隆元素.children()//选择所有的孩子.remove()//移除所有孩子.end()//再次回到被选元素.文本();

    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>
    

    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".

    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?

    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.

    解决方案

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

    Code provided for easy reference:

    $("#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天全站免登陆