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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With