Help me implementing addClassName in my JavaScript project the right way
I find myself often needing addClassName and removeClassName functions for Element
s. However, I dare not to extend the native Element
due to potential collisions. So, now I am wondering what to do.
I took a look at ExtJS, and it achieves this like:
var element = document.getElementById('...');
var elem = new Ext.Element(element);
elem.addClass('something');
I like the idea of not extending the native Element
here, but I do not really like the idea of wrapping the element so hard over a custom object, because now I can't do several things like setAttribute
easily, for example:
var element = document.getElementById('...');
var elem = new Ext.Element(element);
elem.addClass('something');
elem.setAttribute('src', '...'); // Fails
However, I could do:
var element = document.getElementById('...');
element.setAttribute('src', '...');
var elem = new Ext.Element(element);
elem.addClass('something');
but to me this does not l开发者_运维问答ook really nice. It looks a bit complex instead.
Are there any other alternative ways I could use besides wrapping the element around my own object that offers me these cool methods?
Just check if there's already an implementation defined. I'm pretty sure addClassName
is not going to have a different signature than you have at the moment.
if (!node.prototype.addClassName) {
node.prototype.addClassName = function addClassName(name) {
// your code
}
}
精彩评论