-1

I want to get the texts in my div but not the texts in child div.

I have

html

  <div id='textDiv'>
       texts I want to get
          <span id='textChildDiv'>
             texts I don't want
          </span>
    </div>

jquery

  $('#textDiv').click(function(){
       alert($(this).text())  //will get 'texts I want to gettexts I don't want'
       //I only want 'texts I want to get' to be returned.
    })

I found

http://viralpatel.net/blogs/jquery-get-text-element-without-child-element/

for my soulution but it seems there are better approach than his way.

Any ideas? Thanks a lot!

FlyingCat
  • 14,036
  • 36
  • 119
  • 198

3 Answers3

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

DEMO: http://jsfiddle.net/VcghZ/

VisioN
  • 143,310
  • 32
  • 282
  • 281
2

Try using .contents and fetch the text node alone. See below,

DEMO: http://jsfiddle.net/pyaAN/

    var result = '';
    $('#textDiv').contents().each(function () {
        if (this.nodeType == 3 && $.trim($(this).text()).length > 0) {
            result += this.nodeValue;
        }
    });
Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134
2

Try using

$('#textDiv').click(function(){

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

As in this fiddle: http://jsfiddle.net/jQf6d/

David Müller
  • 5,291
  • 2
  • 29
  • 33
  • Since David is the first one reply. I will give him green! thanks for all the helps guys. all +1 – FlyingCat Nov 28 '12 at 22:13
  • @FlyingCat Well, in fact you can get the exact time of answer by hovering time value which is above author's name and avatar. It should give you the right sequence of answers. – VisioN Nov 29 '12 at 00:52