Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change element style dynamically with puppeteer

I am trying to get an element and set its font size with puppeteer

    const browser = await puppeteer.launch({args: ['--no-sandbox', '--disable-setuid-sandbox']});
    const page = await browser.newPage();
    const html = `<html></html><body style="width:2000">
                  <span class="text">${text}</span>
                  </body></html>`
    await page.setContent(html)
    await page.waitForSelector('.text');
    let textContent = await page.$('.text')
    textContent.style.fontSize = 150 + 'px'

This gives me an error, is it possible to achieve what I am trying to?

like image 666
Petran Avatar asked Sep 18 '25 06:09

Petran


1 Answers

Use ElementHandle.evaluate(fn) in this case. So you should do it like this

let textContent = await page.$('.text');
await textContent.evaluate((el) => el.style.fontSize = 150 + 'px');
like image 89
Sarsa Murmu Avatar answered Sep 19 '25 18:09

Sarsa Murmu