jQueryの代わりにdocument.querySelectorを使う
jQueryはIDやクラスを指定してDOMエレメントが取得できるので便利に使っている人は多いかと思います。しかし、DOMの取得だけであれば素のJavaScriptでも簡単にできます。それがdocument.querySelectorです。
他にもIDを指定する document.getElementById 、クラスを指定する document.getElementsByClassName 、タグ名を指定する document.getElementsByTagName など何種類もあるのが分かりづらさを感じさせる原因ですが、document.querySelector と document.querySelectorAll はすべてを兼ね備えます。
ということで今回は document.querySelector / document.querySelectorAll の使い方を紹介します。
document.querySelector と document.querySelectorAll の違い
二つのメソッドの違いは返ってくるのが複数かどうかです。 document.querySelector は最初の一つしか返ってきません。クラスやリストを指定しても最初の一つだけです。それに対して document.querySelectorAll は一致するDOMすべてが返ってきます。
document.querySelectorの使い方
document.querySelector は引数にCSSセレクタを指定します。これはjQueryで使ってきたものをそのまま使えます。
This file contains 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
document.querySelector('.hoge') |
返ってくるのはDOMです。
ない時には nullが返ってくる
注意点としては該当するDOMがなかった場合には null が返ってくるので、メソッドチェーンが使えません。それに対してjQueryの場合はメソッドチェーンが可能です。
This file contains 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
document.querySelector('.hoge').innerText // エラー | |
$('.hoge').text() // 空文字 |
これをいちいち判定しながら作るのはちょっと面倒でしょう。
簡単な関数でラップする
そこで document.querySelector を直接使わず、簡単な関数でラップしてあげます。
This file contains 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
function $(selector, doc) { | |
let dom = null; | |
let target = doc || document; | |
const plural = !(selector.match(/^.*#[a-zA-Z0-9\-_\.]+$/)); | |
if (plural) { | |
dom = target.querySelectorAll(selector); | |
} else { | |
dom = target.querySelector(selector); | |
} | |
if (plural) { | |
if (dom.length > 0) return dom; | |
} else { | |
if (dom) return dom; | |
} | |
dom = document.createElement('div') | |
dom.$ = function(selector) { | |
return $(selector, dom) | |
}; | |
return plural ? [dom] : dom; | |
} |
これはごくごく簡単な例ですが、存在しないCSSセレクタを指定してもある程度のメソッドチェーンが書けるようになります。
document.querySelectorやdocument.querySelectorAll、そしてそれがエラーを起こさないためのやり方さえ覚えてしまえばjQueryを使うことなくDOM操作を行えるようになります。jQueryは他にもたくさんの機能があって便利ですがAngularやReact、Vueとの相性が良くなかったり、使っていない機能の方が多くなりがちです。jQueryで使っているのがDOM操作ばかりだ…という方はdocument.querySelectorに乗り換えても良いでしょう。
コメントは受け付けていません。