Cheerio - how to get full recursive html of a selector that returns multiple items?

Viewed 18

If one does

//=>  <ul id="fruits">
//      <li class="apple">Apple</li>
//      <li class="plum">Plum</li>
//      <li class="apple">Apple TOoo</li>
//      <li class="pear">Pear</li>
//    </ul>
$('.apple').html();

it will output only

 <li class="apple">Apple TOoo</li>

but, I want to get the html of all the elements returned combined, currently it only returns the first, as according to the docs: Gets an HTML content string from the first selected element. https://cheerio.js.org/classes/Cheerio.html#html

How do I do this with Cheerio? If I use the top level .html(node) with a specific node, then if it has subchildren, they render as Object[Object].

But, .text() traverses the whole list of results and combines them. text() doesn't look at the first element only. What is the equivalent for .html()? Alternatively, I don't mind combining the string results of multiple html() calls, but then the children being rendered as literal Object strings messes up the whole thing.

1 Answers

I found that I could have just been using Cheerio.load(..) to load the html instead of trying to render it from each node itself.

let nodes = Cheerio.load(theHtmlBody)('.apple');

return nodes.map( (i, el) => Cheerio.load(el).html() ).get().join("\n");

Thanks to @PA.'s comments above

Related