Dive Into Greasemonkey

Teaching an old web new tricks

4.15. Setting an element's style

If you only need to set a few styles on a single element, you can do this “manually” by setting various subproperties on the element's style property.

Example: Setting style on a single element

This presumes that there is an element whose ID is "logo".

var logo = document.getElementById('logo');
logo.style.marginTop = '2em';
logo.style.backgroundColor = 'white';
logo.style.color = 'red';
[Warning]

The property names of individual styles are not always obvious. Generally, they follow the same pattern, where margin-top becomes someElement.style.marginTop. But there are exceptions: the float property is set with someElement.style.cssFloat, since “float” is a reserved word in Javascript.

← Getting an element's style
Post-processing a page after it renders →