我认为这很简单,但它给我带来了一些问题,因为简单地将标签值替换为另一个标签值。我正在获取 HTML 代码,并将 className 添加到每个 H 标签,但我还需要将其更改为从旧存储的 html 到我的 nextJs 项目的所有 h3 标签,
起始代码
<h1>Header one</h1>
<h2>header two </h2>
我需要他们
<h3>Header one</h3>
<h3>header two </h3>
当前代码除注明外均有效
let desc= '
<h1>Header one</h1>
<h2>header two </h2>';
const $ = cheerio.load(desc);
$("p").addClass("my-4");
$("h1").replaceWith("h3"); // <-- Not the desired result here
$("h1").addClass("text-3xl font-semibold my-6 md:text-4xl");
$("h2").addClass("text-3xl font-semibold my-6 md:text-4xl");
$("h3").addClass("text-3xl font-semibold my-6 md:text-4xl");
$("h4").addClass("text-3xl font-semibold my-6 md:text-4xl");
$("h5").addClass("text-3xl font-semibold my-6 md:text-4xl");
$("h6").addClass("text-3xl font-semibold my-6 md:text-4xl");
我想你正在寻找这样的东西:
const cheerio = require("cheerio"); // ^1.0.0-rc.12
const html = `<h1>Header one</h1><h2>Header two</h2>`;
const $ = cheerio.load(html);
$("h1, h2").replaceWith((_, e) => `<h3>${$(e).html()}</h3>`);
console.log($.html());
输出:
<html><head></head><body><h3>Header one</h3><h3>Header two</h3></body></html>
Cheerio 与 jQuery API 兼容,支持
replaceWith()
的函数参数。
您可以使用它来抓取内容并将其插入到新的
<h3>
元素中
$('h1,h2').replaceWith(function() {
return $(`<h3>${$(this).html()}</h3>`);
});