Search code examples
javascriptpolyfills

How to polyfill element's methods?


Many times I find that I need methods that are not so widespread among browsers. I know I don't need a polyfill to solve this everytime but I think they are usefull and I'd like to know the steps to implement them.

In this case, i'd like to polyfill the element.closest() method, but this is just an example. Notice my question here is not how to polyfill that method in particular but how to add that method to every new element from querySelector.

Obviously the first step is cheking for support:

if(!document.querySelector("body").closest){
  //Now that we know the method is not available,
  //we should modify the global methods of every new selection
  //so that it includes the new method.
}
function closest(property, value){
  while (x = x.parentElement) { 
    if (x[property] == value) return x;
  }
  return null;
}

My question is about how to connect this to blocks. Could you help me?


Solution

  • Okay, so you have your polyfill function ready. Now, you need to inject it to the node object.

    Node.prototype.closest = closest;
    

    To check if it is working:

    if (typeof Node.prototype.closest == "undefined") {
      Node.prototype.closest = function () {
        console.log("Hi");
      }
    }
    

    If you wanna do this to the elements, you need to use HTMLElement object:

    if (typeof HTMLElement.prototype.closest == "undefined") {
      HTMLElement.prototype.closest = function () {
        console.log("Hi");
      }
    }
    

    Then you can call:

    document.closest();
    a = document.querySelector("#one-element-with-id");
    a.closest();