4

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 "

000
  • 26,951
  • 10
  • 71
  • 101
Ωmega
  • 42,614
  • 34
  • 134
  • 203

3 Answers3

6

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

rahul
  • 7,573
  • 7
  • 39
  • 53
  • 2
    Note that that `Node` (and therefore `Node.TEXT_NODE`) is not defined in IE7 or IE8, so this code will fail in those browsers. You should define the constants yourself if you want to "modernize" those browsers, or use the literal '3'. `Node` is defined as of IE9. – manzoid Oct 10 '12 at 13:20
5

http://jsfiddle.net/SGZW4/

var text = $("#d1").contents().filter( function() {
    return this.nodeType === 3;
}).text();
Esailija
  • 138,174
  • 23
  • 272
  • 326
2

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.

Blazemonger
  • 90,923
  • 26
  • 142
  • 180
  • 1
    Thank you for improving my version. I understood the question wrong and thought OP wants the new content of `#d1` to be `text` :) – halex Oct 10 '12 at 13:13