Get all child nodes of div using cheerio?

时间:2016-04-21 22:27:14

标签: javascript jquery node.js 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']

1 个答案:

答案 0 :(得分:3)

您可以尝试使用mapfilter方法。

例如:

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

基本上在回调功能中,你需要使用if's来获得你想要的东西。