mehdi
mehdi

Reputation: 9502

how to filter text inside HTML tag using jQuery

I want to grab text inside a div element like this :

<div class='someclass'> 
<blockquote>some text ! </blockquote>
another text goes here . 
</div>

so I get all text with jQuery like this:

var qtext = $('.someclass').text(); 

I want to exclude text that's in child elements, e.g. <blockquote>some text ! </blockquote>. I just need the text inside div element. How can I filter that ?

Upvotes: 1

Views: 3927

Answers (3)

Christian C. Salvad&#243;
Christian C. Salvad&#243;

Reputation: 827536

What you want is only to select the TextNodes:

var textNodes =   $('.someclass').contents()
                                 .filter(function() {
                                   return this.nodeType ==  Node.TEXT_NODE;
                                 });

That will give you an array of TextNodes, you could then extract the actual text content of all the nodes to an array:

var textContents = $.map(textNodes, function(n){return n.textContent;});

Upvotes: 0

user434917
user434917

Reputation:

This a workaround :

var div = $('.someclass').clone();
div = div.find('blockquote').remove().end();
alert(div.text());

Upvotes: 1

James Skidmore
James Skidmore

Reputation: 50308

See "strip HTML tags": http://devkick.com/blog/parsing-strings-with-jquery/

Upvotes: 1

Related Questions