the previous post might raise the question, why are we interested in named stylesheets? HTML pages can have two different types of stylesheets linked to them. stylesheets with no title attribute are persistent, and are always applied to the page. stylesheets with a title are alternative, and a browser can choose which one is applied. one of these should have a relation attribute of rel=”stylesheet” which indicates the default (preferred) stylesheet, while the others have rel=”alternate stylesheet”. with some clever use of CSS, you can use this to provide several alternate “skins” for your website. with a browser which supports it, or some clever use of javascript, you can provide a visitor with the means to choose one and have it apply across your entire website.

thus, javascript code to obtain a list of named stylesheets. it works by using the prototype function $$() to get a list of all link elements in the page, then selects only those which are matched by the named_link() function, and finally maps those through the link_meta() function. named_link() checks whether a link’s relation attribute includes the fragment ‘style’, and whether it has a (not empty) title attribute. link_meta() returns an anonymous object containing a link element and its title attribute (which we’re most interested in).

with that foundation, we can determine which of the named stylesheets is the default (preferred) stylesheet by finding the first one whose relation attribute does not include the fragment ‘alt’.

  function get_prefcss () {
    if (css = list_stylesheets().find(pref_css)) return css.title;
  }
  function pref_css (meta) {
    return (meta.link.readAttribute('rel').indexOf('alt') == -1);
  }

we can also determine which of the named stylesheets is currently active, via the DOM attribute ‘disabled’. this attribute is set to false for the active named stylesheet, and true for all other named stylesheets.

  function get_actcss () {
    if (css = list_stylesheets().find(active_css)) return css.title;
  }
  function active_css (meta) {
    return (! meta.link.disabled);
  }

finally, with that bit of insight, we can also set which of the named stylesheets is active. the function simply loops through each named stylesheet, and compares the stylesheet’s title attribute to the title we’ve specified. if it matches, then it sets that stylesheet’s disabled attribute to false, otherwise to true. it also notes and returns which stylesheet was marked active, for verification.

  function set_actcss (title) {
    var actcss = false;

    list_stylesheets().each(function (meta) {
      if (meta.title == title) {
        meta.link.disabled = false;
        actcss = title;
      } else {
        meta.link.disabled = true;
      }
    });
    return actcss;
  }

on to part 3…