André
André

Reputation: 2142

How to decorate querySelector/querySelectorAll in JS

I am using PhantomJS to get and evaluate websites. Inside the evaluation, I heavily use querySelector(selector) and querySelectorAll(selector). As the website's HTML sometimes changes, I had to change the selectors or add new selectors for once in a while. Now I am not sure which selectors are still in use and which are code that no longer runs and can be removed.

I would like to decorate these methods and log the selectors that have been used inside the decorated functions. I guess this would be much better than adding all the log-handling inside the main code. Any idea how to achieve this?

Upvotes: 2

Views: 70

Answers (1)

t.niese
t.niese

Reputation: 40842

You need to overwrite the querySelector and querySelectorAll in the prototype of the HTMLElement and HTMLDocument object. But you for sure need store/keep the original function so that you won't break the code.

You could do something like this:

(function() {
  function wrapQueryFunction(name) {
    [HTMLElement, HTMLDocument].forEach(function(obj) {
      //store the original function
      var origQueryFunction = obj.prototype[name];

      //replace the function with the own wrapper
      obj.prototype[name] = function(selector) {
        logSelector(this, selector);
        //call the original function and return the result
        return origQueryFunction.apply(this, arguments);
      }
    });


    function logSelector(elm, selector) {
      console.log('selector: ' + selector);
    }
  }

  wrapQueryFunction('querySelector');
  wrapQueryFunction('querySelectorAll');
}());

Upvotes: 1

Related Questions