Ashwin
Ashwin

Reputation: 12421

How to get innertext which is not enclosed in any html tag

My html is -

​<div>
    <span>spanText</span>
    nonspantext
</div>
​​​​​​

My js is -

​$(function(){
    alert($("div").text());
});​

What I want to get is "nonspantext" as alert.
Fiddle to begin is here - http://jsfiddle.net/UHr2x/

Upvotes: 2

Views: 368

Answers (2)

Florian Margaine
Florian Margaine

Reputation: 60767

Well, that's quite a good use case to use good old DOM API.

$('span')[0].nextSibling.nodeValue;

And a working example.

Seems more efficient than James' solution.

Upvotes: 1

James Allardice
James Allardice

Reputation: 165971

You can use .contents() to get the contents (including text nodes) of an element, and then filter the result to leave only the text nodes:

$("div").contents().filter(function () {
    return this.nodeType === 3;  
}).text();

Here's a working example. Notice that the result includes new lines, so you might want to trim it before using it.

Upvotes: 7

Related Questions