Chrome DevTools:$(选择器)速记不返回元素,而$$(选择器)[0]返回元素
使用
$Chrome API速记为document.querySelector时,我经常遇到一个奇怪的现象,即它没有使用正确的选择器返回元素,而使用$$却可以正常工作。由于puppeteer严重依赖这些速记(page.$、page.$$、page.$eval、page.$$eval),因此可能会导致意外问题。
此问题甚至可以在此处转载,目前位于堆栈溢出(2020年9月29日)。
例如:
$('h1').innerText=>;undefined$$('h1')[0].innerText=>;Chrome DevTools: $(selector) shorthand doesn't return the element...
原因是什么,使用$$的解决方法为什么有效?
解决方案
我发现它会影响那些在前端使用jQuery库的页面(Stack Overflow目前正在使用它)。
在这样的页面上,$被jQuery占据(作为其自身的别名),因此Chrome API返回一个对象,而不是$(selector)的元素。第一个元素是DOM元素本身,这就是[0]工作的原因。
顺便说一下:$$(selector)[0]甚至可以替换为$(selector)[0],因为这个问题与querySelector与querySelectorAll无关。
使用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
它可能对其他人有用。
相关文章