2

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();?

2
  • 1
    What do you mean "like x.hello()"? Commented Oct 8, 2012 at 7:47
  • @Jon: Probably x.hello = function(){hello();} or another horrid code construct. Commented Oct 8, 2012 at 7:49

4 Answers 4

3

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'));
Sign up to request clarification or add additional context in comments.

7 Comments

I'll advice you to not modify the prototype of Element
@Nick: Prototyping DOM elements isn't a good idea. It's not supported by IE 8 and below (I don't know about IE9) and because DOM elements are host objects, they aren't required to comply with your modifications.
add a function to a DOM object, like if I have hello() assign it to x and make it x.hello();
To every DOM element on the page? Then you should modify prototype. To particular - use just assignment.
|
2

If 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

Comments

1
x = document.getElementById("test");
x.prototype.hello = function() { // your function }

Now you can use x.hello().

Comments

1

Check this out.

The link takes you a sample script on jsfiddle.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.