Extract the Text in a Element with JQuery

南楼画角 提交于 2019-11-30 09:12:18

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.

This does it (tested):

    var clone = $("#bla > span").clone();
    clone.find('strong').remove();
    alert(clone.text());

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.

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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!