みかづきブログ・カスタム

基本的にはちょちょいのほいです。

jQueryのclosestをjQuery無しで使いたい時は、Element.closestの出番 🔍

f:id:kimizuka:20201020140350p:plain

jQueryのclosetとは

querySelectorは己の子要素を検索するメソッドですが、closetは逆に己の親を検索する、jQueryオブジェクトのメソッドです。

api.jquery.com

Given a jQuery object that represents a set of DOM elements, the .closest() method searches through these elements and their ancestors in the DOM tree and constructs a new jQuery object from the matching elements.

https://api.jquery.com/closest/#closest-selector より引用

DOM要素のセットを表すjQueryオブジェクトが与えられると、.closest()メソッドはDOMツリー内のこれらの要素とその祖先を検索し、一致する要素から新しいjQueryオブジェクトを構築します。

Google翻訳にて翻訳

非常に便利なメソッドなので、jQueryを導入した際はよく使っていたのですが、最近はjQueryを使う機会もめっきり少なくなり、これだけのために導入するのも嫌なので、自作しようと思いました。

一応、npmでそれっぽいものを検索してみると、

www.npmjs.com

ありました。人気もあるし、自分で作らなくて良さそうです。

これを導入しかけたんですが、一応、JavaScriptに実装されて無いかも探してみると、

developer.mozilla.org

ありました。同名で。closest。

var el = document.getElementById('div-03');

var r1 = el.closest("#div-02");
// id=div-02 である要素を返す

こんな感じで使えるようです。これで良いですね。

IEには存在しないメソッドのようですが、

if (!Element.prototype.matches) {
  Element.prototype.matches = Element.prototype.msMatchesSelector ||
                              Element.prototype.webkitMatchesSelector;
}

if (!Element.prototype.closest) {
  Element.prototype.closest = function(s) {
    var el = this;

    do {
      if (Element.prototype.matches.call(el, s)) return el;
      el = el.parentElement || el.parentNode;
    } while (el !== null && el.nodeType === 1);
    return null;
  };
}

という感じで、IE9以上用のポリフィルも公開されてます。抜かりなしです。