Search code examples
javascriptnode.jscheerio

.find is not a function on cheerio object


  let playersCell = `
    <td class="foo" colspan="2">
      <a href="example.com">
        <span class="bold">John Beluga</span>
         - Sarah Jay.
       </a>
    </td>
    `

let players = cheerio.load(playersCell)
players.find('a').html()

I try to load a html string into cheerio.js and find an a tag, but I am getting

[TypeError: players.find is not a function]

Console.log shows for players

enter image description here


Solution

  • find is a method that appears on DOM search results. You need to create a result before you can use find.

    For example:

    let playersCell = `<table><tr>
        <td class="foo" colspan="2">
          <a href="example.com">
            <span class="bold">John Beluga</span>
             - Sarah Jay.
           </a>
        </td></tr></table>
        `
    
    let players = cheerio.load(playersCell);
    console.log(players('td').find('a').html());
    <script src="https://wzrd.in/standalone/cheerio@latest"></script>

    But in this case, there is no need to. You can just use the initial search directly:

    let playersCell = `
        <td class="foo" colspan="2">
          <a href="example.com">
            <span class="bold">John Beluga</span>
             - Sarah Jay.
           </a>
        </td>
        `
    
    let players = cheerio.load(playersCell);
    console.log(players('a').html());
    <script src="https://wzrd.in/standalone/cheerio@latest"></script>