Ωmega
Ωmega

Reputation: 43673

How to get text inside of container that is not part of children

Let's have html code like this:

<div id="d1"><span>1.</span>Hallo <span>Kitty, </span><div>How are you?</div></div>

It is just example, there may be different children elements inside.

How can I get text inside of d1 container that is not part of children elements?

For the example above it shold be just "Hallo "

Upvotes: 4

Views: 728

Answers (3)

rahul
rahul

Reputation: 7663

this will work for you

$('#d1')
  .contents()
  .filter(function() {
    return this.nodeType == Node.TEXT_NODE;
}).text()

or you can use this as suggested below for old browser support also

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

Demo

Upvotes: 6

Blazemonger
Blazemonger

Reputation: 92893

Improving on halex's trick, you can take advantage of the fact that .children() finds only DOM nodes and ignores text nodes:

var text = $('#d1').clone().children().remove().end().text(); // string "Hallo "

...but I prefer the .nodeType technique, because it's more clear what you're doing.

Upvotes: 2

Esailija
Esailija

Reputation: 140230

http://jsfiddle.net/SGZW4/

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

Upvotes: 5

Related Questions