I thought this would be simple but its causing me some issue in simpley replacing tag valuse with another. I am taking HTML code, and adding className to each H tag but I also need to change the to all h3 tags moving from legacy stored html ro my nextJs project,
starting code
<h1>Header one</h1>
<h2>header two </h2>
I need them to be
<h3>Header one</h3>
<h3>header two </h3>
current code all works except the noted
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");
I think you're looking for the
replaceWithcallback version, which lets you wrap the desired HTML tag on theinnerHTMLof the matched element dynamically, rather than a hardcoded string:Output: