简体   繁体   中英

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

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, '');

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/

$("span")
    .clone()
    .children()
    .remove()
    .end()
    .text();

should do it

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

remove a tag and get the span contents. 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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM