Skip to content
Advertisement

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?

Advertisement

Answer

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!');
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement