Moonboy
Moonboy

Reputation: 219

Extending DOM elements

Im working on a jQuery/Zepto slider plugin and wanted ask you about extending dom elements. I know that this method is not very elegant for different browsers environment but its make life so much easier.

Also to make names unique ive added all methods into one object 'pluginName'

So each slider item will get a set of custom methods:

item = document.createElement('div');
itemMethods(item); // add methods to item element

itemMethods = function(el){
 el.pluginName= {};
 el.pluginName.getIndex = function(){};
 el.pluginName.setLocalData = function(){};
 el.pluginName.getLoaclData = function(){};
}

Is this method worth a try? Are there any huge issues with custom element methods? Im not sure am i going to right direction. Thanks

Upvotes: 2

Views: 354

Answers (2)

Danilo Valente
Danilo Valente

Reputation: 11342

Notice that document.createElement('div'); returns an instance of HTMLDivElement:

var div = document.createElement('div');
console.log(div, div.constructor === HTMLDivElement);  // HTMLDivElement, true

Therefore, you can extend the HTMLDivElement class by simply adding properties to its .prototype object:

HTMLDivElement.prototype.pluginName = {};
HTMLDivElement.prototype.pluginName.getIndex = function () {};
HTMLDivElement.prototype.pluginName.getLocalData = function () {};
HTMLDivElement.prototype.pluginName.setLocalData = function () {};

Or even shorter:

HTMLDivElement.prototype.pluginName = {
    getIndex: function () {},
    getLocalData: function () {},
    setLocalData: function () {}
};

EDIT If you just want to add new methods to a single div, try the following:

var itemMethods = function (el) {
    var index = 0;
    var data = {};
    el.pluginName = {
        getIndex: function () {
            // access the element by el
        },
        getLocalData: function () {
            // access the element by el
        },
        setLocalData: function () {
            // access the element by el
        }
    };
};

item = document.createElement('div');
itemMethods(item); // add methods to item element

Upvotes: 1

Johan
Johan

Reputation: 35194

Since you mentioned jQuery, how about something like this:

var $div = $('<div/>').data({ 
    pluginName: { 
        doStuff: function(s){ console.log('hello ' + s); } 
    } 
});

$div.data('pluginName').doStuff('world');

http://jsfiddle.net/LHk8j/

Upvotes: 0

Related Questions