Cheerio: Copy the functionality of outerHTML

Created on 19 Apr 2012  路  4Comments  路  Source: cheeriojs/cheerio

I'm using cheerio on my node.js server, and using the method html() I can copy the functionality of innerHTML, but I haven't found a way to copy how outerHTML works. How could I do this?

Thanks :)

Most helpful comment

You can use $.html() to render the whole string or $.html([Cheerio Object]) to render the outerHTML of a specific element.

All 4 comments

You can use $.html() to render the whole string or $.html([Cheerio Object]) to render the outerHTML of a specific element.

The thing is, I'm using it inside an each function, like this:

$(element).each(function(index, elem) {
console.log($(this).html());
});

And in that case, it gives back the equivalent to innerHTML. I suppose this is because elem is a Cheerio Object instead of a string indicating the element. But I can't find how to manipulate this element to get the outer HTML. Thanks!

Oh okay, so you'll want to do something like this:

$(element).each(function(index, elem) {
  var $this = $(this);
  console.log($.html($this));
});

Keep in mind cheerio is try to emulate jQuery as close as possible so $(...).html() in jQuery returns innerHTML. $.html() is non-standard, but really useful for server-side HTML manipulation.

Now I get it :P Thanks a lot for your help!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

rajkumarpb picture rajkumarpb  路  3Comments

bxqgit picture bxqgit  路  3Comments

collegepinger picture collegepinger  路  3Comments

francoisromain picture francoisromain  路  5Comments

trevorfrese picture trevorfrese  路  4Comments