10

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?

2
  • the "standard" way should be $("#bla > span:not(strong)").text(); but it is not working with me :-/ I need more search :D Commented Jun 19, 2009 at 10:53
  • 1
    +1 for really interesting question :) Commented Jun 19, 2009 at 12:10

4 Answers 4

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

How do you append this text to an attr? Like <div class="classname" ref="I want this text">
6

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.

Comments

5

This does it (tested):

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

6 Comments

yeahh but 2 many steps :) I was trying to find a only and clean way.
+1 "works". Plus, it's clean. And easy to read. Clarity over one-liners?
So I get an up-vote then a (possibly tactical?) downvote. Nice.
How is a down vote tactical? Even with it you are the top voted answer.
@Paolo, I did say possibly. I just get annoyed when a working, tested solution that's taken a good 20 minutes or so of my weekend (in Bahrain it is Fri+Sat) gets an immediate insult.
|
0
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>

1 Comment

-1 this will output "bla bla blaI want this text", he does specify the output should be "I want this text" only!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.