Such Much Code
Such Much Code

Reputation: 827

Is there a pure Javascript equivalent to jQuery's $.fn.extend?

In jQuery I do this:

$.fn.extend({
   hello: function() {console.log(this + ' says hello world.')}
});

and then

$('div').hello();

Can I do this in pure javascript without loading the whole jQuery just for that?

Upvotes: 4

Views: 2811

Answers (2)

Jagdish Bharathi
Jagdish Bharathi

Reputation: 11

In Javascript too, you can extend selector functions by hooking up to the prototype of HTML Element native functions. For example, I would use the below code for your problem:

HTMLDivElement.prototype.hello = function()
  {
    console.log(this+" says hello world.");
  }
document.querySelector('div').hello()

for an Anchor element, I would do this:

HTMLAnchorElement.prototype.my_func=function()
  {
    console.log(this.nodeName);
  }
document.querySelector("a").my_func()

The above code would print the node name of the selected anchor element in the browser console. You can explore other HTML selector functions using plain Javascript.

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement

Upvotes: 1

ralh
ralh

Reputation: 2564

Well, technically you could do something like this:

function extendingQuerySelector(selector, extension) {
    var el = document.querySelector(selector);
    for(var key in extension) {
        if(extension.hasOwnProperty(key)) {
            el[key] = extension[key];
        }
    }
    return el;
}

Though it doesn't seem like a good idea to extend basic DOM objects. There's no jQuery wrapper around it here, though you could of course make such a wrapper.

Upvotes: 1

Related Questions