Element.stylize via Prototype.js
Posted: May 25th, 2007 Tags: Javascript, Web developmentI often want to add a bunch of styles to an element, so I wrote a stylize method so I can do something like this:
$("foo").stylize({
color: red,
background-color: green,
text-decoration: underline
});
Implementing stylize is easy with Prototype’s Element.addMethods() method:
var ElementExtensions = {
stylize: function(element, styles) {
for (var s in styles) {
element.style[s] = styles[s];
}
return element;
}
}
Element.addMethods(ElementExtensions);
Update: Prototype 1.6 added a similar setStyle method which works similarly but also allows CSS string-type style declaration (e.g., myElement.setStyle(”color: blue; border: 3px”)). Still, the above is a nice example of Element.addMethods().