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.
-
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
1 Answer
Reset to default 15You 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>