How to add my own methods to HTMLElement object?

后端 未结 4 1521
你的背包
你的背包 2020-11-27 22:25

For example for this.parentNode I would like to just write this.p or instead of document.getElementById(\'someid\') just write d

相关标签:
4条回答
  • 2020-11-27 22:32

    This article from perfectionkills.com will probably give you some insight into how it's done, and why you shouldn't do it.

    (By the way, jQuery doesn't extend DOM elements. They use DOM wrappers instead.)

    0 讨论(0)
  • 2020-11-27 22:39

    I would strongly suggest not attempting to do this, for a few reasons:

    • Browser compatibility. While it is possible in several browsers, it isn't possible in IE <= 8.
    • DOM elements are host objects. Host objects (i.e. those provided by the environment that aren't native JavaScript objects) have no obligation to play by the same rules as native JavaScript objects and other than specified DOM behaviour can essentially do what they like. So, even if some browsers provide an HTMLElement prototype and allow you to augment it, there's no guarantee that it will work as you expect.
    • Compatibility with other code in your page. If any other code in your page (such as Prototype) messes with the HTMLElement prototype, you risk naming collisions and hard-to-detect bugs.

    Instead, I would suggest creating wrapper objects around DOM nodes as jQuery, YUI and other libraries do.

    Kangax has written a good article on this, covering all these points and more.

    0 讨论(0)
  • 2020-11-27 22:44

    Although you can prototype on the HTMLElement in many browsers - Internet Explorer (6,7,8) is NOT one of them. AFAIK, IE9 does support this (though I haven't tested it).

    For browsers that do handle it, you can do:

    HTMLElement.prototype.doHello = function(thing){
      alert('Hello World from ' + thing);
    };
    
    0 讨论(0)
  • 2020-11-27 22:45

    In a word, don't. It is best not to modify objects you don't own.

    This is particularly true for HTMLElement, which you cannot modify in some browsers.

    0 讨论(0)
提交回复
热议问题