如何解决如何使用cheerio设置outerHTML
有人可以回答我,如何使用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 的文档中的某些内容? 请指出我做错的地方。
问候,奥莱
解决方法
使用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>")
})
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。