0

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>
Jabli
  • 31
  • 4
  • 1
    Wouldn't a templating library like ejs be better for this? The use case here is rather confusing. Wouldn't the user type in "John" and "Smith" rather than "newName"? `await dynamicElements.each` [doesn't do what you think it does](https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop)--you'd have to use a traditional loop. – ggorlen Feb 23 '23 at 16:52
  • @ggorlen Thanks for providing a link, it helped me to understand how async/await loops work. I see now that giving variable name: "newName" as an example may be a little confusing. Basiclly I need to read HTML files and make certain fields dynamic using Sightly. E.g. "John" should be a variable like ${firstName} because users have diffrent names, however

    Species: Human

    should stay as it is, cause everyone is human.
    – Jabli Feb 24 '23 at 08:52

0 Answers0