Using HTMLElement.prototype

In the DOM structure, each HTML element is considered as a child of the more general HTMLElement interface, which is an object whose instances are actually markup elements. Like any other object in JavaScript, even this object has a prototype object that can be augmented to add new methods and properties to any HTML element on the page. The syntax is as follows:

HTMLElement.prototype.method = function() {};

For example, suppose that we have a simple unordered list with three items. We want to add some styles to the second item. The underlying markup is as follows:

<ul id="test">

We define some CSS classes for that purpose:

.test1 {border: thick solid red;}
.test2 {background: orange; padding: 0.5em;}

Our JavaScript code will be the following:

HTMLElement.prototype.addClass = function(theClass) {
 return this.className = theClass;

window.onload = function() {
 var test = document.getElementById('test');
 test.getElementsByTagName('li')[1].addClass('test1 test2');

And this is the result:

As you can see, everything works as expected. However, since it's always risky to augment the core interfaces of JavaScript objects, the best thing you can do before doing so is checking whether the method you're adding is already present or not.

Leave a Reply

Note: Only a member of this blog may post a comment.