Jquery: return html from div, not children

If I click on #parent, I want to return the text inside it, and not return the text inside the attached layers file ( #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"

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

+3
source share
2 answers

You can capture it as follows:

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

You can check here , you may need it $.trim(), but like that .

Another alternative is a loop, although text nodes, for example:

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

You can check it out here or the cropped version here .

+4
source

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

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

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

+4

Source: https://habr.com/ru/post/1768623/


All Articles