让前端飞Web前端之路

pure Javascript implementation o

2020-04-01  本文已影响0人  柳正来

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

上一篇 下一篇

猜你喜欢

热点阅读