views:

42

answers:

2

If I click on #parent I want to return the text inside it and not return the text inside nested
layers (#child-parent, #child)

<div id='parent'>
   this text is for parent

   <div id='child-parent'> 
     this text if for child-parent  

       <div id='child'>
        and this text is for child.   
       </div>   

   </div>

</div>


this:
$('#parent').html() = "this text is for parent"

and not this:
$('#parent').html() = "this text is for parent this text is for child-parent and this text is for child"

+4  A: 

You can grab it like this:

$('#parent').clone().children().remove().end().html()

You can test it out here, you may want a $.trim() call on there though, like this.

Another alternative is to loop though the text nodes, like this:

$('#parent').contents().filter(function() { return this.nodeType == 3; }).text()

You can test that here or the trimmed version here.

Nick Craver
@Nick Craver: wow, thank you very much!!
dany
Thanks a lot, I've discovered existence of three new jquery methods :)
Nikita Rybak
+4  A: 

If the structure always looks like this, you can call:

var mytext = $('#parent').contents().first().text();

Example: http://www.jsfiddle.net/YjC6y/

jAndy
@jAndy: thanks alot!
dany