Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

148
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda