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.
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>
Species: Human
should stay as it is, cause everyone is human. – Jabli Feb 24 '23 at 08:52