4

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?

Such Much Code
  • 787
  • 1
  • 9
  • 26
  • possible duplicate of [Javascript object extending -](http://stackoverflow.com/questions/10430279/javascript-object-extending) – kosmos Jul 30 '15 at 09:16
  • 1
    "Can I do this in pure javascript without loading the whole jQuery just for that?" — Yes. Look at jQuery's source code to see how they did it. – Quentin Jul 30 '15 at 09:23

2 Answers2

1

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.

ralh
  • 2,514
  • 1
  • 13
  • 19
1

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