最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I click display:none element with puppeteer? - Stack Overflow

programmeradmin4浏览0评论

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

Code:

page.click(".foo");

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

Code:

page.click(".foo");
Share Improve this question edited Apr 29, 2019 at 16:09 Thomas Dondorf 25.3k6 gold badges96 silver badges112 bronze badges asked Apr 29, 2019 at 16:00 invalidinvalid 1,5154 gold badges16 silver badges35 bronze badges 4
  • 1 I don't know puppeteer but can't you just set its display to block? github./GoogleChrome/puppeteer/issues/… – Mosh Feu Commented Apr 29, 2019 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). – user1171983 Commented Apr 29, 2019 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 Commented Apr 30, 2019 at 0:43
  • Does this answer your question? Puppeteer in NodeJS reports 'Error: Node is either not visible or not an HTMLElement' (particularly the second answer which is identical to the accepted answer here) – ggorlen Commented Dec 31, 2021 at 5:27
Add a ment  | 

3 Answers 3

Reset to default 12

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();
});

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;
  }

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

await page.$eval('.foo', el => el.click())
发布评论

评论列表(0)

  1. 暂无评论