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

199
Views
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 answers
Answer question

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 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!