Jack Johnson
Jack Johnson

Reputation: 1535

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']

Upvotes: 3

Views: 9718

Answers (1)

Kiril
Kiril

Reputation: 331

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.

Upvotes: 8

Related Questions