Extract the Text in a Element with JQuery

2019-02-06 17:02发布

I want to extract the Text inside a Element with JQuery

<div id="bla">
    <span><strong>bla bla bla</strong>I want this text</span>
</div>

I want only the text "I want this text" without the strong-tag. How can I do that?

4条回答
太酷不给撩
2楼-- · 2019-02-06 17:40
var textFromSpanWithoutStrongTag = $('div#bla > span').text();

UPDATED:

var textFromSpanWithoutTextFromStrongTag =
    $('div#bla > span').text().replace($('div#bla > span > strong').text(), '');

UPDATED:

var text = '';
$("div#bla > span").contents().each(function () {
    if(this.nodeType == 3) text = text + this.nodeValue; });

Tested in FF3, IE8, O10b on:

<div id="bla">
    <span>
        <strong>bla bla bla</strong>
        I want this
        <strong>bla bla</strong>
        text
        <span>bla bla bla</span>
    </span>
</div>
查看更多
Fickle 薄情
3楼-- · 2019-02-06 17:49

This does it (tested):

    var clone = $("#bla > span").clone();
    clone.find('strong').remove();
    alert(clone.text());
查看更多
家丑人穷心不美
4楼-- · 2019-02-06 17:55

Try this...

<script type="text/javascript">
//<![CDATA[
$(document).ready(function(){
    $("#bla span").contents().each(function(i) {
        if(this.nodeName == "#text") alert(this.textContent);
    });
});

//]]>
</script>

This doesn't need to remove any other nodes from context, and will just give you the text node(s) on each iteration.

查看更多
smile是对你的礼貌
5楼-- · 2019-02-06 17:59

Variation on karim79's method:

$("span").clone().find("strong").remove().end().text();

or if you just want the root text without knowing what other tags are in it:

$("span").clone().children().remove().end().text();

still a little long, but I think this about as short as you can hope for.

查看更多
登录 后发表回答