简体   繁体   中英

How can I get the innerHTML of an anchor tag using Cheerio?

I want to parse some data from an HTML page. A simplified example follows.

When I run the following code I expect it to return [ "foo", "baz", "quux", ] but instead it throws "TypeError: anchorNode.html is not a function".

Fails
const HTML = `
  <a href="foobar">foo</a>
  <a href="bar">baz</a>
  <a href="qux">quux</a>
`;
const $ = Cheerio.load( HTML, );
const result = [];
const $a = $( 'a' );
$a.each(( i, anchorNode, ) => {
  const innerHtml = anchorNode.html();
  result.push( innerHtml, );
});
return result;

It's interesting to note that the following code works as expected.

Succeeds
const HTML = `
  <a href="foobar">foo</a>
  <a href="bar">baz</a>
  <a href="qux">quux</a>
`;
const $ = Cheerio.load( HTML, );
const result = [];
const $a = $( 'a' );
$a.each(( i, link, ) => result.push( link.attribs.href ));
return result;
// result: ["foobar","bar","qux"]

What am I doing wrong? How do I get the first function to behave as expected?

As stated in comments by Barmar -

It should be $(anchorNode).html() . anchorNode is a DOM element, not a jQuery object.

anchorNode is viewed as a DOM element. This means that the native functions are only of the type https://www.w3schools.com/jsref/dom_obj_all.asp . You can fix this by wrapping anchorNode in $(). IE $(anchorNode).html()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM