0

I have:

<div id="container">
    <div class="comment_text">
        <a>Blah blah</a> THIS IS WHAT I NEED
    </div>
</div>

I want to get the text THIS IS WHAT I NEED from the above div, this is what I do usually:

var val = $.trim($('#container').find('.comment_text').text());

but this also gets the a tag, so how I should get only the text? I'm thinking of next() but it's not working:

 var val = $.trim($('#container').find('.comment_text a').next().text());

Thanks

3
  • something like: var val = $.trim($('#container').find('.comment_text a').text()); should work Commented Jun 18, 2013 at 11:35
  • @user123_456 but it's not! Commented Jun 18, 2013 at 11:36
  • even with .comment_text a? notice this a tag Commented Jun 18, 2013 at 11:37

4 Answers 4

7

Getting unwrapped textnodes with jQuery is a bit more involved :

$('#container .comment_text').contents().filter(function() {
    return this.nodeType === 3;
}).text();

FIDDLE

You should propably trim that as well.

You could also do:

$('#container .comment_text a').get(0).nextSibling.nodeValue;

FIDDLE

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

1 Comment

It's not, did you open your console ?
2

You need to clone the div and remove the anchor then you'll get the text :

var clone = $('.comment_text').clone();
clone.find('a').remove();

var val = $.trim(clone.text());

Comments

2
$('#container').clone().find('a').remove().end().text();

You can remove the anchor temporarily to get the remaining text, and by cloning it you don't interrupt the DOM elements.

3 Comments

@adeneo sorry, i forgot .clone() var txt = $('#container').clone().find('a').remove().end().text(); jsfiddle.net/GrDBz/4
Now it would work, but why it's a community wiki is still beyond me ?
Sorry, did it quickly on my phone while I was out the door. Thanks to the Community for the edit; Yes, needs to be found first, then removed.
-1

You can try the following:

var val = $.trim($('.comment_text').find("a").html();

Comments

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.