Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cheerio: Loop over children with tags [duplicate]

I am attempting to loop over the children of a tag and I want to retain their respective tags. For example:

<div class='main'>
    <p>First p</p>
    <div class='1'>Div 1</div>
    <div class='2'>Div2 <p>Another P</p></div>
</div>

I would like to loop over the children like so:

<p>First p</p>
<div class='1'>Div 1</div>
<div class='2'>Div2 <p>Another P</p></div>

The code I am attempting is like so:

const block = body.find('div.main')
const children = block.children().each((i, el) => {
   console.log("===")
   console.log($(el).html()) //Also tried $(this).html(), but returns null
})

Results:

===
First p
===
Div 1
===
Div2 <p>Another P</p>

But the result gives me everything inside each child, which is not what I want. I would like to retain their respective <p> or <div> tags.

Other attempts of using outerHTML somehow doesn't seem to work, ie they all returned undefined. Things I have tried:

console.log($(el).prop('outerHTML'));
console.log($(el).outerHTML);
console.log($(el)[0].outerHTML);
like image 229
Koh Avatar asked Dec 04 '25 18:12

Koh


1 Answers

Managed to solve it by using cheerio.html($(el)) instead, that is as indicated in their documentation here

This achieve a very similar result to outerHTML.

like image 190
Koh Avatar answered Dec 06 '25 07:12

Koh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!