< Day Day Up > |
Hack 7. Alter a Page's Style
There are four basic ways to add or modify a page's CSS rules. In many of the user scripts I've written, I want to make things look a certain way. Either I'm modifying the page's original style in some way, or I'm adding content to the page and I want to make it look different from the rest of the page. There are several ways to accomplish this. 1.8.1. Adding a Global StyleHere is a simple function that I reuse in most cases in which I need to add arbitrary styles to a page. It takes a single parameter, a string containing any number of CSS rules: function addGlobalStyle(css) { try { var elmHead, elmStyle; elmHead = document.getElementsByTagName('head')[0]; elmStyle = document.createElement('style'); elmStyle.type = 'text/css'; elmHead.appendChild(elmStyle); elmStyle.innerHTML = css; } catch (e) { if (!document.styleSheets.length) { document.createStyleSheet(); } document.styleSheets[0].cssText += css; } } 1.8.2. Inserting or Removing a Single StyleAs you see in the previous example, Firefox maintains a list of the stylesheets in use on the page, in document.styleSheets (note the capitalization!). Each item in this collection is an object, representing a single stylesheet. Each stylesheet object has a collection of rules, and methods to add new rules or remove existing rules. The insertRule method takes two parameters. The first is the CSS rule to insert, and the second is the positional index of the rule before which to insert the new rule: document.styleSheets[0].insertRule('html, body { font-size: large }', 0);
You can also delete individual rules by using the deleteRule method. It takes a single parameter, the positional index of the rule to remove. The following code will remove the first rule, which we just inserted with insertRule: document.styleSheets[0].deleteRule(0); 1.8.3. Modifying an Element's StyleYou can also modify the style of a single element by setting properties on the element's style attribute. The following code finds the element with and sets its background color to red: var elmModify = document.getElementById("foo"); elmModify.style.backgroundColor = 'red';
There is no easy way to set multiple properties at once. In regular JavaScript, you can set multiple styles by calling the setAttribute method to the style attribute to a string: elmModify.setAttribute("style", "background-color: red; color: white; " + "font: small serif"); However, as explained in "Avoid Common Pitfalls" [Hack #12], this does not work within Greasemonkey scripts. |
< Day Day Up > |