Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all child nodes of div using cheerio? [duplicate]

<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']
like image 206
Jack Johnson Avatar asked Feb 01 '26 02:02

Jack Johnson


1 Answers

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.

like image 188
Kiril Avatar answered Feb 02 '26 14:02

Kiril



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!