簡體   English   中英

使用cheerio獲取div的所有子節點?

[英]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>

所以我有了上面使用$('div.hello')獲得的以上內容。 我想遍歷它。 如何遍歷包括文本節點在內的所有內容? 我嘗試使用$('div.hello').contents()但這不是抓取文本節點(“ Text1”,“ Text4 Block”和“ Last Text5”)。我的最終目標是基本上拆分HTML塊當我到達第一個具有“ bye”類的元素時,因此我想要一個包含以下html字符串的數組,

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

您可以嘗試使用地圖過濾器方法。

例如:

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

基本上在回調函數中,您需要使用if's來獲得所需的內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM