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

147
Views
Refactor method chaining javascript

I call a function with bunch of nested method, i'm using web scraping tools called cheerio and i want to get the text out of it so i need to call a bunch of function. here's my example code.

        var text = $(el)
          .children()
          .first()
          .children()
          .first()
          .children()
          .first()
          .text()
          .replace(/\s\s+/g, " ");

My question is, how can i simplify my function so I have the same result without chaining my function?

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

0

A naive solution could be

var text = $(">*:nth-child(1)".repeat(3), el).text().replace(/\s+/g, " ");

For a good solution we'd need more context. Like what does the markup look like.

about 4 years ago · Juan Pablo Isaza Report

0

You can use nth-child(1) selector for the select first child.

You can use like that

$("div div:nth-child(1) div:nth-child(1) ul:nth-child(1)").text()
about 4 years ago · Juan Pablo Isaza Report

0

Use a loop

let child = $(el).children().first()
if (child) {
 while (child.children().first()) {
   child = child.children().first()
 }
 child.text().replace(/\s\s+/g, " ");
}
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!