6

I want to click an element which display property is none. How can I do this?

Code:

page.click(".foo");
Thomas Dondorf
  • 23,416
  • 6
  • 84
  • 105
invalid
  • 1,215
  • 4
  • 13
  • 30
  • 1
    I don't know puppeteer but can't you just set its `display` to `block`? https://github.com/GoogleChrome/puppeteer/issues/2514#issuecomment-387467169 – Mosh Feu Apr 29 '19 at 16:04
  • 1
    I would question why you would want to click on it, since `display: none;` implies it's inaccessible (eg. it's removed from the accessibility tree). –  Apr 29 '19 at 16:08
  • The link I want to click is normaly display:none, and it will be display:block by some actions like moov mouse to near the link whitch position is different by user because they custom design. And page.$() doesn't work for element with display:none. – invalid Apr 30 '19 at 00:43
  • Does this answer your question? [Puppeteer in NodeJS reports 'Error: Node is either not visible or not an HTMLElement'](https://stackoverflow.com/questions/51857070/puppeteer-in-nodejs-reports-error-node-is-either-not-visible-or-not-an-htmlele) (particularly the [second answer](https://stackoverflow.com/a/66537619/6243352) which is identical to the [accepted answer here](https://stackoverflow.com/a/55907070/6243352)) – ggorlen Dec 31 '21 at 05:27

3 Answers3

11

You can use the JavaScript click function. This function will trigger the elements click event and does not care about whether the element is visible or not.

You need to use page.evaluate to execute it inside the page.

Example:

await page.evaluate(() => {
  document.querySelector('.foo').click();
});
Thomas Dondorf
  • 23,416
  • 6
  • 84
  • 105
0

Problem is still actual, did not worked for me using: await page.evaluate(() => { document.querySelector('.foo').click(); });

After spending at least half day, I made a small trick with changing CSS 'display' property to 'inherit', click() an element, and revert CSS 'display' back to original.

  let inputCheckBox = await document.querySelector("input[type='checkbox']");

  const cssDisplay = inputCheckBox.style.display;
  if (!cssDisplay || 'none' === cssDisplay) {
     inputCheckBox.style.display = 'inherit';
  }

  await inputCheckBox.click();

  if (cssDisplay !== inputCheckBox.style.display) {
     inputCheckBox.style.display = cssDisplay;
  }
Dmitri Algazin
  • 3,332
  • 27
  • 30
0

A variation on Thomas's answer using $eval for a more compact code.

await page.$eval('.foo', el => el.click())