Checking an element is disabled using Puppeteer

demouser123 picture demouser123 · Jul 25, 2018 · Viewed 9.1k times · Source

I have a button that has an initial state of disabled -

<button type = "submit" class="ant-btn ant-btn-primary ant-btn-lg" disabled>

The disabled attribute is not present once the conditions are met - so the HTML becomes

<button type = "submit" class="ant-btn ant-btn-primary ant-btn-lg">

I want to check that the button has attribute disabled, however since the attribute has no value in it, I am not able to find to a way to do so.

For example, if the disabled attribute had something like this

<button type = "submit" class="ant-btn ant-btn-primary ant-btn-lg" disabled = "disabled">

then I can do something like this

let button = await page.$('button');
let valueHandle = await input.getProperty('disabled');
assert.equal(await valueHandle.jsonValue(), 'disabled');

but since there is no value for the attribute, how to proceed in this case?

Answer

Grant Miller picture Grant Miller · Jul 26, 2018

Here's a comprehensive solution showing how to solve your problem using:

page.$(), page.$$(), page.$eval(), page.$$eval(), page.$x(), and page.evaluate().

// Using page.$()
const is_disabled = await page.$('button[disabled]') !== null;

// Using page.$$()
const is_disabled = (await page.$$('button[disabled]')).length !== 0;

// Using page.$eval()
const is_disabled = await page.$eval('button[disabled]', button => button !== null).catch(error => error.toString() !== 'Error: Error: failed to find element matching selector "button[disabled]"');

// Using page.$$eval()
const is_disabled = await page.$$eval('button[disabled]', buttons => buttons.length !== 0);

// Using page.$x()
const is_disabled = (await page.$x('//button[@disabled]')).length !== 0;

// Using page.evaluate()
const is_disabled = await page.evaluate(() => document.querySelector('button[disabled]') !== null);