Chrome DevTools:$(selector) shorthand 没有 return 元素,而 $$(selector)[0] 有

Chrome DevTools: $(selector) shorthand doesn't return the element while $$(selector)[0] does

有时我会遇到一个奇怪的现象,$ chrome api shorthand document.querySelector 但 return 具有正确选择器的元素,同时它与 $$ 一起正常工作。由于 puppeteer 严重依赖于这些 shorthand(page.$page.$$page.$evalpage.$$eval),它可能会导致意外问题。

这个问题现在甚至可以在 Stack Overflow 上重现 (09-29-2020)。

例如:

它的原因是什么,为什么 $$ 的解决方法有效?

我发现它会影响那些在前端使用 jQuery 库的页面(Stack Overflow 目前正在使用它)。

在这样的页面上,$ 被 jQuery(作为其自身的别名)占用,因此 chrome api returns 一个对象而不是$(selector) 的元素。第一个元素是 DOM 元素本身,这就是 [0] 起作用的原因。

顺便说一句:$$(selector)[0] 甚至可以用 $(selector)[0] 代替,因为这个问题与 querySelectorquerySelectorAll.[=29= 无关]

页面使用 jQuery:

$('h1'):

n.fn.init(2) [h1.grid--cell.fs-headline1.fl1.ow-break-word.mb8, h1#feed-modal-title.s-modal--header.fw-bold.js-first-tabbable.c-move, prevObject: n.fn.init(1), context: document, selector: "h1"]

$('h1')[0] / document.querySelector('h1'):

<h1>...</h1>

页面使用jQuery:

...虽然在页面上不依赖于 jQuery 它照常工作。

$('h1') / document.querySelector('h1'):

<h1>...</h1>

$('h1')[0]:

undefined

它可能对其他人有用。