4

How do I do something like the following, but only for DOM objects, not all objects:

Object.prototype.hide = function() {
  this.style.display = 'none';
};

Please use only pure JavaScript, no jQuery or other third-party libraries.

Also, please comment on your solution's standards & cross-browser compatibility.

6
  • 2
    You should use jQuery, or another library. If you dont' do this, you're doing it wrong. Commented Mar 11, 2011 at 17:46
  • 3
    @Stefan: I'm the biggest proponent of jQuery you'll find, but even I won't say something like that. Doing it "wrong"? No. Very probably doing it wrong and in a more convoluted way? Almost definitely. Almost. Commented Mar 11, 2011 at 17:50
  • No. You're doing it wrong. I don't build web-apps with assembly, and I don't build anything that touches the DOM without a framework/library. Commented Mar 11, 2011 at 17:52
  • For IE compatibility, you'll have to use a wrapper object or some other inventive technique. In the end, <your favorite library here> probably does this, so unless you're doing this for learning, it's probably not worth the effort. Commented Mar 11, 2011 at 17:53
  • 4
    @Stefan: Don't be so dogmatic. DOM is not that hard, even allowing for browser differences, and doing without jQuery or equivalent is perfectly viable if you know what you're doing. As for the comparison between assembly and... what? JavaScript? ... that's just a bit silly. Commented Mar 11, 2011 at 18:49

2 Answers 2

6

Elements in the DOM use HTMLElement as their prototype - so in an ideal world you would just add to this.

HTMLElement.prototype.hide = function() {
    this.style.display = 'none';
};

BUT: This doesn't work in IE, so no go I'm afraid.

Sign up to request clarification or add additional context in comments.

Comments

1

Suggested reading for this is the way prototype extends the DOM.

And for an idea inside the code (which is too large to reproduce here) you can find here (Search for Element.extend).

In two words, they cannot extend the objects from start, so they extend them with each of their functions that return DOM elements.

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.