'How can I add a css class to an element with Puppeteer
tried code below returned Error: Evaluation failed: TypeError: Cannot read properties of undefined (reading 'add'). The class 'form-control' is on all inputs
const forms = ".form-control";
if (device.name === "Panel") {
await page.evaluate((s) => {
let dom = document.querySelectorAll(s);
dom.classList.add("_has_error");
}, forms);
}
Solution 1:[1]
querySelectorAll returns an array of elements. You can try dom.classList is undefined indeed as the error says, but dom[0].classList gives valid DOM token list.
You need to iterate over the dom array, e.g. with Array.forEach() if you want to apply your class on every matching elements:
let dom = document.querySelectorAll(s);
dom.forEach(el => el.classList.add("_has_error"));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | theDavidBarton |
