Search code examples
javascriptjquerynode.jscheerio

Get all child nodes of div using cheerio?


<div class="hello">
  Text1
  <li>Text2</li>
  <div class="bye">Text3</div>
  Text4 Block
  <div class="bye">Text5</div>
  Last Text5
</div>

So I have the above which I grab in cheerio using $('div.hello'). I want to iterate through it. How do I iterate through everything including the text nodes? I tried using $('div.hello').contents() but this isn't grabbing the text nodes("Text1, "Text4 Block", and "Last Text5"). My end goal is to basically split the HTML block when I reach the first element that has a class of "bye". So I want an array holding the following html strings,

final_array = ['Text1 <li>Text2</li>', '<div class="bye">Text3</div> Text4 Block <div class="bye">Text5</div> Last Text5']

Solution

  • You could try to use map or filter methods.

    For example:

    var text = $('div.hello').contents().map(function() {
        if (this.type === 'text')
            return $(this).text().trim()
    }).get()
    

    Basically in callback function you need to play with if's to get what you want.