Home > database >  Replacing each node in cheerio selector
Replacing each node in cheerio selector

Time:12-25

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

CodePudding user response:

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

  • Related