For example for this.parentNode
I would like to just write this.p
or instead of
document.getElementById('someid')
just write document.g('someid')
. Of course that are simple examples, I just want to know what is the correct way to do it.
(I know I can use jQuery or Prototype, but I'd like to learn how it is really done in JS)
Customized built-in elements inherit from basic HTML elements. To create one of these, you have to specify which element they extend (as implied in the examples above), and they are used by writing out the basic element but specifying the name of the custom element in the is attribute (or property).
All standard rules of HTML elements apply to custom elements. Just like standard elements, you can create a custom element in the DOM using JavaScript, or declare it in HTML.
AppendChild. The simplest, most well-known method of appending an element to the DOM is certainly the appendChild() .
Autonomous custom elements are new HTML tags, defined entirely by the author. They have none of the semantics of existing HTML elements, so all behaviors need to be defined by the author. Customized built-ins extend existing HTML elements with custom functionality. They inherit semantics from the elements they extend.
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){ console.log(this + ' says: ' + thing) } document.body.doHello('hello')
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.
I would strongly suggest not attempting to do this, for a few reasons:
HTMLElement
prototype and allow you to augment it, there's no guarantee that it will work as you expect.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 DOM extensibility, covering all these points and more.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With