-
-
Save kawaz/daa5b304293a64ffabba7a27dbbec8e2 to your computer and use it in GitHub Desktop.
document.querySelectorAll のショートハンド関数。NodeList じゃなくて配列で返してくれます。::shadow に自前対応済み!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // const q = (s,r)=>[...(r||document).querySelectorAll(s)]; | |
| const q = (selector,root) => | |
| selector.split(/::shadow\s*/) | |
| .reduce((parents,selector,idx) => | |
| parents.flatMap(parent => | |
| selector=="" ? (idx==0?parent:parent.shadowRoot) : [...(idx==0?parent:parent.shadowRoot).querySelectorAll(selector)] | |
| ) | |
| , [root||document] | |
| ) |
あ、自分は使ってなかったので漏れてたけどカンマ区切りセレクタには未対応だね。対応は難しくないけどまーいいや。
::shadow が深すぎて面倒なとき用の奴も作った(作り途中)
https://gist.github.com/kawaz/391d03249c20286ce965e198e87ec356
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
昔は querySelectorAll のセレクタで
custom-tag::shadow h1とか書けばカスタムエレメント内のDOMも一発で走査できたのに、Chrome のどこかのバージョンから::shadowがnullを返すようになって一発で引っ張れなくなってしまったので自分用にコピペで使ってた便利関数を修正した 。基本的には querySelectorAll のショートハンドな感じでCSSセレクタを引数にすると配列で返してくれる奴です。
ユーザスクリプトとかで元々 querySelector じゃなくこの
qを使ってたので、コピペ用の関数定義だけ差し替えるだけで::shadow問題が一発で解決してくれて幸いだった。