首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用cheerio设置outerHTML

如何使用cheerio设置outerHTML
EN

Stack Overflow用户
提问于 2021-02-25 12:23:16
回答 1查看 220关注 0票数 1

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

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

代码语言:javascript
复制
<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解析并添加一些操作

代码语言:javascript
复制
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替换,但是只有spans被p替换,我想得到结果:

代码语言:javascript
复制
<p>totally new html structure</p>
<p>totally new html structure</p>

但下一个

代码语言:javascript
复制
<div class="page-info">
   <p>totally new html structure</p>
</div>
<div class="page-info">
   <p>totally new html structure</p>
</div>

我是不是遗漏了什么在文件里给啦啦队?请指出我做错了什么地方。

你好,奥利

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-25 13:01:54

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

代码语言:javascript
复制
$(".page-info").replaceWith("<p>totally new html structure</p>");

使用each

代码语言:javascript
复制
let elemList = $(".page-info");
elemList.each((i, elem)=> {
   $(elem).replaceWith("<p>totally new html structure</p>")
})
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66368408

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档