Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

201
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda