How to run inquirer.prompt on every occurance of element using cheerio library?

76 views Asked by At

I'm currently developing the console application which allows users to change the values inside HTML files. I'm using the cheerio library to find in the HTML file every occurrence of the class called "dynamic" and next I want the user to assign a new value for each element.

But when I run .each() method on the cheerio object I end up being able to only assign value to the last occurrence, and then all the previous ones are assigned the same value I just provided for the last one. As I mentioned before, I want the user to input the new value for each occurrence separately one by one.

Can only assign value for the last one All the previous occurances get the same value as the last one

Here is my code:

async function readFile(htmlPath) {
        const htmlFile = fs.readFileSync(htmlPath, 'utf8');
        // Load the HTML into Cheerio
        const $ = cheerio.load(htmlFile);
        const dynamicElements = $('body').find('.dynamic');
        // Log the contents of each dynamic element
        await dynamicElements.each(async (i, el) => {
            await nameVariable($(el).text());
        });
        return $.html();
    }

async function nameVariable(value) {
    await inquirer.prompt({
        type: "input",
        name: "variableName",
        message: `Name the variable for value:${value} =>`,
        default: "variableName",
    },).then((r) => {
        return r.variableName;
    });
}

Here is also the html file:

<html>
<head>
    <title>Example HTML File</title>
    <meta charset="utf-8"/>
</head>
<body>
<div>
    <p>First Name : </p>
    <p class="dynamic">John</p>
    <p>Last Name :</p>
    <p class="dynamic">Smith</p>
    <p class="static">Species: Human</p>
</div>
<ul>
    <li class="dynamic">List Item 1</li>
    <li>List Item 2</li>
    <li>List Item 3</li>
    <li>List Item 4</li>
</ul>

</body>
</html>
0

There are 0 answers