I'm starting to develop a small JavaScript library and I want to make styling of HTML elements possible only through my API (because for some reason I need to have full control over styling).
So I want to make style
property inaccessible (my API will access it through my style
alias - not an ideal solution, but for other libraries like jQuery it will do the trick).
If I write this (inspired by this topic):
var box = document.getElementById('someElementId');
Object.defineProperty(box, 'style', {
get: function() {
throw 'you cant access style property';
}
});
box.style.color = 'red';
it works for box
element only.
Is it possible to do this for all (existing and future) elements in Webkit, Firefox, and IE9+?
I've also tried this:
Object.defineProperty(HTMLElement, 'style', {...
but no luck.
Any help would be greatly appreciated!
Edit
As @Teemu suggested I can write HTMLElement.prototype
instead of HTMLElement
, and it works fine in FF and IE, but not in Chrome. And it looks like a Chrome bug. Sadly...
Edit2 - why do I need it
The main goal of a library I want to develop is to allow writing styles like:
element.setWidth('parent.width / 2 - 10');
In this case element
's width should react on each changing of the parent
's width.
But since onresize
event is available only for window
object (this article seems to be obsolete),
the only way I can "listen" modifying .style.width
property is to perform my own API for styling.
And I want to restrict (or at least show warning) direct style
modifying because it will break the elements' behavior.