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

200
Vistas
Replacing each node in cheerio selector

I'm using cheerio.js to parse some HTML documents, but I'm facing certain problems.

The thing is the HTML file I am using contains the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>
    
    </title>
</head>
<body>
    <p>Text 1</p>
    <p>Text 2</p>
</body>
</html>

Now, I also have a javascript array of Items like this:

var items = ["<h2>orange</h2>", "<h2>mango</h2>"];

What I want to do is simply replace each P tags with the respective item in the items array, i.e something to this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>
    
    </title>
</head>
<body>
    <h2>orange</h2>
    <h2>mango</h2>
</body>
</html>

What I tried so far:

var selections = $("p");

for ( let index = 0; index < selections.length; index++ ) {

  selections[index].replaceWith(items[index])    

}

But it says that function replaceWith() is not valid

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Solution:

using the each method, one can easily process particular elements

solving the above problem:

var items = ["<h2>orange</h2>", "<h2>mango</h2>"];

$("p").each((index, element) => $(element).replaceWith(items[index])) Basically the each method will invoke a callback function where element is the selector of that particular element, and index is the position of the item in that selection.

For more ref, check: https://cheerio.js.org/classes/Cheerio.html#each

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