Search code examples
javascriptnode.jsnode-fetch

How to get a certain element from a body?


I use node-fetch , and I get the body of the site this way:

import fetch from 'node-fetch';

(async () => {
    const response = await fetch('link');
    const body = await response.text().

    console.log(body);
})()

The console displays the full body of the entire page. But I want to get a specific element with a certain class. How do I change the code to do this?


Solution

  • You can use cheerio.js. It is an implementation of jQuery for node.

    The below code selects an h2 and changes its text to Hello World.

    const cheerio = require('cheerio');
    const $ = cheerio.load(body);
    
    $('h2').text('Hello World!');