Vanilla JavaScript .closest without jQuery

前端 未结 3 797
庸人自扰
庸人自扰 2020-12-07 00:34

I\'m working on an application that only has jQuery 1.1 installed which dosn\'t support the .closest method.

My script currently looks like this:

$(\         


        
3条回答
  •  忘掉有多难
    2020-12-07 00:49

    Cause IE still does not support element.closest() the simplest thing to do is use include the polyfill from MDN Element.closest() . Include it at the very beginning of your javascript codes.

    For browsers that do not support Element.closest(), but carry support for element.matches() (or a prefixed equivalent, meaning IE9+), include this polyfill:

    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;
      };
    }
    

    However, if you really do require IE 8 support, then the following polyfill will do the job very slowly, but eventually. However, it will only support CSS 2.1 selectors in IE 8, and it can cause severe lag spikes in production websites.

    if (window.Element && !Element.prototype.closest) {
      Element.prototype.closest =
      function(s) {
        var matches = (this.document || this.ownerDocument).querySelectorAll(s),
            i,
            el = this;
        do {
          i = matches.length;
          while (--i >= 0 && matches.item(i) !== el) {};
        } while ((i < 0) && (el = el.parentElement));
        return el;
      };
    }
    

提交回复
热议问题