【问题标题】:How to set outerHTML with using of cheerio如何使用cheerio设置outerHTML
【发布时间】:2021-05-27 19:21:29
【问题描述】:

有人可以回答我,如何使用cheerio 正确设置元素的outerHTML。 我对此有意见。

示例:假设我在下面有一个 HTML 结构

<div class="page-info">
   <span>Here is an example #1</span>
</div>
<div class="page-info">
   <span>Here is an example #2</span>
</div>

通过cheerio对其进行解析并添加一些操作

const cheerio = require('cheerio');
const $ = cheerio.load(`above HTML is here`);

let elemList = $('.page-info');
for (const elem of elemList) {
   let innerHtml = $(elem).html(); //<span>Here is an example #1</span>
   let outerHtml = $.html(elem); //<div class="page-info"><span>Here is an example #1</span></div>
   let replacedHtml = '<p>totally new html structure</p>';

   $(elem).html(replacedHtml);
}

因此,我希望将所有 div 替换为 p。但只有跨度被替换为 p。 我想得到结果:

<p>totally new html structure</p>
<p>totally new html structure</p>

但它是下一个

<div class="page-info">
   <p>totally new html structure</p>
</div>
<div class="page-info">
   <p>totally new html structure</p>
</div>

我是否遗漏了 Cheerio 的文档中的某些内容? 请指出我做错的地方。

问候,奥莱赫

【问题讨论】:

    标签: javascript html node.js npm cheerio


    【解决方案1】:

    使用replaceWith(用内容替换匹配的元素)替换节点:

    $(".page-info").replaceWith("<p>totally new html structure</p>");
    

    使用each

    let elemList = $(".page-info");
    elemList.each((i, elem)=> {
       $(elem).replaceWith("<p>totally new html structure</p>")
    })
    

    【讨论】:

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