Kate Belova
Kate Belova

Reputation: 185

Cheerio get element outer html

I am using cheerio to parse html file on server side with node 6.10.2. I need to get outerHtml of each div inside document body and my code is:

 /* const data is valid html document (type of string)*/
 const $ = cheerio.load(data);
 let pages = $('body > div').toArray();
 console.log(pages[0]); // Elements parsed correctly
 let htmlPages = pages.map(page => $(page).html());
 console.log(htmlPages[0]); // Here I have innerHtml, not outer...      

Problem: I'm getting string with innerHtml. Can anybody help pls. ?

Upvotes: 14

Views: 18089

Answers (3)

Andrey Hohutkin
Andrey Hohutkin

Reputation: 2919

Just get property of html element:

$(page).html().prop('outerHTML')

Upvotes: 2

Johan Willfred
Johan Willfred

Reputation: 851

Change your map func to

let htmlPages = pages.map(page => $.html(page));

according to docs

Upvotes: 40

BrightEyed
BrightEyed

Reputation: 386

If you don't have easy access to the original $ object, the following also works

function outerHTML (element) {
    var index = element.index();
    var parent = element.parent().clone();
    var child = parent.children()[index];
    parent.empty();
    parent.append(child);
    return parent.html();
}

Upvotes: 2

Related Questions