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();?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Well, if you need to add a function to an element, you have to modify it’s prototype:
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:
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?
and so on and so forth.
So, for using this, you’d go something like this: