Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
373 views
in Technique[技术] by (71.8m points)

jquery - Getting text within element excluding decendants

I see that jQuery has the .text() function for getting all text within an element and its descendant elements.

Is there a way to only get the text that is directly within the element?

eg.

<div>
Here is <b>some</b> text.
</div>

From that I would want to get just Here is text.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
var result = $('div').contents().map(function() {
    if( this.nodeType === 3 ) {
        return this.data;
    }
}).get().join('');

Example: http://jsfiddle.net/PeXue/

This uses the contents()[docs] method to get all children of the div, including text nodes, then the map()[docs] method to build a collection of the text contents of only the text nodes (this.nodeType === 3) using their .data property.

After that is done, it makes an Array from the collection using the get()[docs] method, and finally joins the result using .join()[docs].

Of course your selector should be specific to the <div> you're targeting.


EDIT: If you want to normalize the spaces between the words a bit, you can trim the leading and trailing white space from the content of each text node using the jQuery.trim()[docs] method, then give .join() a single space to join each set.

var result = $('div').contents().map(function() {
    if( this.nodeType === 3 ) {
        return $.trim( this.data );
    }
}).get().join(' ');

alert( result );

Example: http://jsfiddle.net/PeXue/1

We could even shorten it a bit, and ensure that any empty text nodes are excluded at the same time:

var result = $('div').contents().map(function() {
    return $.trim( this.data ) || null;
}).get().join(' ');

alert( result );

Example: http://jsfiddle.net/PeXue/2


EDIT 2:

You can get an enormous performance increase by using the jQuery.map()[docs] method, which is meant for more generic use.

var result = $.map( $('div')[0].childNodes, function(val,i) {
  if (val.nodeType === 3) {
    return val.data;
  }
}).join('');

Here's a performance test showing the difference.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...