【问题标题】:Cheerio: Loop through children and call html()Cheerio:循环遍历子元素并调用 html()
【发布时间】:2021-02-16 10:06:34
【问题描述】:

我有以下 HTML 已传递到 Cheerio:

<h1 id="heading1">heading1</h1>
<p>text</p>

$.root().html() 的输出是这样的:

<html><head></head><body><h1 id="heading1">heading1</h1>
<p>text</p>
</body></html>

我需要遍历 body 的子节点并在每个非 h1 子节点上调用 .html() ,并对每个 h1 子节点执行其他操作。

按顺序循环遍历元素很重要,我不能同时选择 body 和 .html() 的所有非 h1 子级。

我试过了:

var children = $("body").first().children();
for(var i = 0; i < children.length; i++){
    console.log(children[i].html()); // children[i].html() is not a function
}

但是从数组中选择一个孩子后我不能调用 .html() 。 .html() 在使用 children.each 时也不是一个函数。

.html() 是一个函数,如果不是使用 [i] 从数组中获取元素,而是使用 .first(),但显然这只适用于第一个元素。

【问题讨论】:

    标签: javascript cheerio


    【解决方案1】:

    这可能就是你要找的,

    var children = $("body").first().children(":not(h1)"); // Select all non-h1 children
    for(var i = 0; i < children.length; i++){
        console.log($(children[i]).html()); // Get jquery object from dom element
    }
    

    【讨论】:

      【解决方案2】:

      你可以使用这个解决方案

      var children = $("body").first().children(/* add your expression as string whether you want the header or not*/);
      
      
      for(var i = 0; i < children.length; i++){
          console.log($(children[i]).html()); 
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-14
        • 2017-02-11
        相关资源
        最近更新 更多