0

I have this HTML from an external website that I need to parse with jQuery. I'm only interested in the text inside the main div (like described in the code).

The problem is, if I use $('#main').text() I get all texts inside the div, even from the nested divs.

<div id="main">  

  <div><h1>....</h1></div>  
  <div>Other Text</div>

  I only want to parse this text

  <div></div>
  <div></div>

</div>

Any advice?

crispychicken
  • 2,592
  • 2
  • 33
  • 50

1 Answers1

1

With Jquery you can use contents() that will give you access to all node elements inside the div, after that you can filter to get just the TextNodes:

var nodeText = $('#main').contents().filter(function(){
  return this.nodeType === 3 && $.trim(this.nodeValue) !== '';
}).text()

console.log(nodeText)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">  
  <div><h1>....</h1></div>  
  <div>Other Text</div>
  I only want to parse this text
  <div></div>
  <div></div>
</div>
DaniP
  • 37,813
  • 8
  • 65
  • 74