39

Hi have noticed a few sites that give the style tag an id such as:

<style id=style-id></style>

Can anyone explain firstly why you would do this and also the benefits of doin so?

David
  • 393
  • 1
  • 3
  • 4

1 Answers1

72

So you can reference it (just like any other element), i.e.

var styles = document.getElementById('style-id');
// do anything you want, like
styles.parentNode.removeChild(styles); // remove these styles
styles.setAttribute('href', 'alternate-styles.css'); // change the style
Dan Beam
  • 3,632
  • 2
  • 23
  • 27
  • 4
    so you can use it to create dynamic styles using javascript then? – David Sep 26 '10 at 09:43
  • Yes, you can add or delete stylesheets, move them up and down in the page's DOM, or possibly even read their contents? (never tried it) You can additionally style individual elements by change their `.style` properties (i.e. `document.body.style.backgroundColor='red';`), but I highly recommend a library for anything major. – Dan Beam Sep 26 '10 at 09:52
  • Really cool way to add new style lines actually. I'm thinking about making a javascript function to add new lines of styles something like `function addStyle(newStyleLine)`, then i will use innerHTML to add the new class. I hope it will work, but i dont have any idea if it will be efficient? – Burak Tokak Dec 27 '14 at 14:13
  • Does removing a ` – Martijn Jul 13 '15 at 14:08
  • This is a pratical use-case: http://stackoverflow.com/questions/15505225/inject-css-stylesheet-as-string-using-javascript – eremzeit Nov 20 '15 at 02:15
  • You can always insert CSS rules to a stylesheet: https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule – webdevinci Dec 14 '16 at 20:20
  • I don't believe `href` is an attribute that can be applied to a ` – Josiah Mar 02 '17 at 19:02