I have a function called hello().
Then I retrieve a DOM element with x = document.getElementById("test");
How can i make this function behave like x.hello();?
Well, if you need to add a function to an element, you have to modify it's prototype:
Element.prototype.hello = function() {
}
which will work for any element however you select it.
Say you would like to change the style of the element, it would be something like:
Element.prototype.hello = function() {
this.style.color = 'blue';
}
As discussed in the comments below, this isn't necessarily a good idea. Here is a blog post that discusses why: http://perfectionkills.com/whats-wrong-with-extending-the-dom/
So, what you can do is create a utilities class that operates on Elements.
What does it look like?
var DOM = {};
DOM.hello = function (element, worldParam) {
element.style.color = worldParam;
}
and so on and so forth.
So, for using this, you'd go something like this:
DOM.hello(document.getElementById('#test'));
ElementIf you want to add a hello() to every DOM element on the page, you should modify its prototype:
Element.prototype.hello = hello;
But I'll not advice you to do so, because your change can affect almost all js code on the page.
If you want to add a hello() to this particular element, simply assign it:
x.hello = hello;
this in hello() will now refer to x
x.hello()"?x.hello = function(){hello();}or another horrid code construct.