How to access the text inside an element while ignoring any text inside the tag next to the text?

What is a good way to get text from a jQuery element when the text itself is adjacent to another element containing text?

In this example, I want to get the text: β€œText I want,” ignoring the text in the adjacent child:

<span> <a>Text I want to ignore</a> Text I want </span> 

My solution was to get all the text in the <span> tag and then remove all the text in the <a> tag. This is a bit inconvenient, so I'm wondering if there is a better way:

 var all_the_text = $('span').text(); var the_text_i_dont_want = $('span').find('a').text(); var text_i_want = all_the_text.replace(the_text_i_dont_want, ''); 
+8
javascript jquery
source share
3 answers

To do this, you need to go to the text nodes:

 var text_i_want = $("span").contents().filter(function(){ return this.nodeType === 3; }).text();​ 

http://jsfiddle.net/UeBZq/

+7
source share
 $("span") .clone() .children() .remove() .end() .text(); 

gotta do it

to give the right credit :) http://viralpatel.net/blogs/jquery-get-text-element-without-child-element/

+5
source share

remove the tag and get the contents of the range. Working demo

 <span> <a>Text I want to ignore</a> Text I want </span>​ var all_the_text = $('span').find('a').remove(); alert($('span').text()); 
+2
source share

All Articles