Cheerio: Loop through children and call html()

I have the following HTML which has been passed into Cheerio:

<h1 id="heading1">heading1</h1>
<p>text</p>

The output of $.root().html() is this:

<html><head></head><body><h1 id="heading1">heading1</h1>
<p>text</p>
</body></html>

I need to loop through the children of body and call .html() on each non-h1 child, and do something else with each h1 child.

It’s important that I loop through the elements in order, I can’t select all non-h1 children of body and .html() them all at once.

I’ve tried this:

var children = $("body").first().children();
for(var i = 0; i < children.length; i++){
    console.log(children[i].html()); // children[i].html() is not a function
}

but I can’t call .html() after selecting a child from the array. .html() is also not a function when using children.each.

.html() is a function if instead of getting the element from the array using [i] I use .first(), but obviously this only works for the first element.

Answer

This is probably what you’re looking for,

var children = $("body").first().children(":not(h1)"); // Select all non-h1 children
for(var i = 0; i < children.length; i++){
    console.log($(children[i]).html()); // Get jquery object from dom element
}