我认为这很简单,但它在简单地用另一个标签值替换标签值时给我带来了一些问题。我正在获取 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");
最佳答案
我认为您正在寻找 replaceWith
回调版本,它可以让您动态地将所需的 HTML 标记包装在匹配元素的 innerHTML
上,而不是硬编码字符串:
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>
关于javascript - Cheerio 将标签值 <h1> 替换为 <h2> 并保留 insideText,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77574909/