Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

210
Views
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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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!');
about 4 years ago · Juan Pablo Isaza Report

0

Well, you've already achieved obtaining a string that contains the entire html of the page.

Now you can write code that extracts the part you want from that string. You said you're wanting to extract an element that has a particular class.

As moonwave99 commented, you could use cheerio, or some other html parser to extract the element with the class name you're targeting.

Or, if you want to avoid using an outside package, you could just write a regular expression to match the HTML element you want from that html string:

let wholeHTML =
`<html>
<p>Paragraph 1</p>
<p class="classIwant">Paragraph 2</p>
<p>Paragraph 3</p>
</html>`;

let rx = /<p class="classIwant".*\/p>/gm;
let matches = wholeHTML.match(rx);
console.log(matches[0]);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!