Skip to content
Advertisement

How to set outerHTML with using of cheerio

could someone answer me, how to properly set outerHTML of element by using cheerio. I have a problem with that.

Example: Let’s say I have an HTML structure below

<div class="page-info">
   <span>Here is an example #1</span>
</div>
<div class="page-info">
   <span>Here is an example #2</span>
</div>

Parsing it via cheerio and adding some manipulations

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);
}

As a result I expect to have all divs to be replaced with p. But only spans are replaced with p. I want to get result:

<p>totally new html structure</p>
<p>totally new html structure</p>

but it’s next

<div class="page-info">
   <p>totally new html structure</p>
</div>
<div class="page-info">
   <p>totally new html structure</p>
</div>

Am I missing something in documentation to the cheerio? Please point me where I’m doing it wrongly.

Regards, Oleh

Advertisement

Answer

Use replaceWith (Replaces matched elements with content) to replace the node:

$(".page-info").replaceWith("<p>totally new html structure</p>");

Using each:

let elemList = $(".page-info");
elemList.each((i, elem)=> {
   $(elem).replaceWith("<p>totally new html structure</p>")
})
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement