When I was writing bookmarklet I found that I can't use those handy Chrome Console APIs like $
, $$
, copy
, so I have to implement them myself.
$
This is similar to document.querySelector
but $
supports the second optional parameter startNode
(see here) but document.querySelector
does not. Instead, we need to use element.querySelector
(see here).
var $ = (selector, startNode) => (startNode || document).querySelector(selector);
$$
This is similar to document.querySelectorAll
.
One caviat is that the returned value is of type NodeList
. It supports APIs like forEach
but doesn't support map
as Array
does. One way to get around it is to wrap it in Array.from
.
var $$ = (selector, startNode) => Array.from((startNode || document).querySelectorAll(selector));
copy
See my other post
网友评论