How do I access text inside an element while ignoring some text inside a tag adjacent to the text?

javascript, jquery

Solution

You have to go to the text nodes for this:

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

http://jsfiddle.net/UeBZq/

Problem

What is a good way to get the text out of a jQuery element when the text itself is adjacent to another element containing text? In this example, I want to get at the text: 'Text I want' while ignoring the text in the adjacent child element: ``` <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 delete all the text in the `<a>` tag. This feels a little awkward 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, ''); ```

Original source

Related problems