最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to turn Cheerio DOM nodes back into html? - Stack Overflow

programmeradmin3浏览0评论

Using the HTML below, I'm attempting to extract the html of each paragraph. However I cannot find any way to turn the nodes back into HTML or query objects.

The below is a string var html = ...

<article>
    <p> p1 </p>
    <p> p2 </p>
</article>

The html is loaded as such

var $ = require('cheerio').load(html)
var paragraphs = $('p').toArray().map(p => /* I want the html at this point */ )

How to I get the HTML of these paragraphs?

NOTE: for clarity I'm calling the return value of cheerio.load a "query object" and the return of the toArray method DOM nodes; for lack of a better phrase.

Using the HTML below, I'm attempting to extract the html of each paragraph. However I cannot find any way to turn the nodes back into HTML or query objects.

The below is a string var html = ...

<article>
    <p> p1 </p>
    <p> p2 </p>
</article>

The html is loaded as such

var $ = require('cheerio').load(html)
var paragraphs = $('p').toArray().map(p => /* I want the html at this point */ )

How to I get the HTML of these paragraphs?

NOTE: for clarity I'm calling the return value of cheerio.load a "query object" and the return of the toArray method DOM nodes; for lack of a better phrase.

Share Improve this question asked Jun 11, 2016 at 18:43 Aage TorleifAage Torleif 2,0131 gold badge22 silver badges42 bronze badges 4
  • Element.outerHTML? – gcampbell Commented Jun 11, 2016 at 18:52
  • 'outerHTML' is not a property of the node. And before it es up, yes I have the latest version of Cheerio :P – Aage Torleif Commented Jun 11, 2016 at 18:55
  • outerHTML is a standard property on DOM elements. – gcampbell Commented Jun 11, 2016 at 18:57
  • You're absolutely right. It is! But I'm asking about how to use Cheerio for this. I can do it with JSDOM just fine. – Aage Torleif Commented Jun 11, 2016 at 19:09
Add a ment  | 

1 Answer 1

Reset to default 15

You can use $.html:

var paragraphs = $('p').toArray().map(p => {
    console.log($.html(p));
    return $.html(p);
});

The documentation shows an example using a selector, however cheerio DOM elements also work as expected:

If you want to return the outerHTML you can use $.html(selector):

$.html('.pear') //=> <li class="pear">Pear</li>

发布评论

评论列表(0)

  1. 暂无评论