Reputation: 827
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
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
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