Currently reading: Black Like Me by John Howard Griffin

Add domain name to every site's root class list

As a purveyor of userstyles, I found myself wanting to change a tiny thing here or there on various sites without giving them each their own tiny stylesheet. I also didn't want to start adding random selectors to a global stylesheet and identifying them by comment; I wanted to identify sites by their domain, e.g. html.apnews-com and keep all styles for that site nested underneath. In order to do this, I think a userscript needs to be involved.

// ==UserScript==
// @name        Global: CSS Domain/URL Support
// @namespace   Violentmonkey Scripts
// @match       *://*/*
// @grant       none
// @version     1.6.1
// @author      chairmanbrando
// @run-at      document-start
// @description Runs as soon as possible to add the page's domain as a class on the `<html>` element.
// ==/UserScript==

const limit = 3; // Check for something and change this as needed.
let hn      = window.location.hostname.split('.');
let su      = null; // One subdomain allowed.

while (hn.length > limit) {
  hn.shift();
}

if (hn.length === 3) {
  su = hn.shift();
}

hn = hn.join('-');

if (hn === '0-1') {
  hn = 'localhost';
  su = null;
}

// Do the thing!
function addClassToDamnedRootElement() {
  if (su && su !== 'www') {
    document.documentElement.classList.add(su);
  }

  document.documentElement.classList.add(hn);
}

// Add our handy class as soon as possible…
addClassToDamnedRootElement();

// …but also watch for changes and reapply if necessary. These JS frameworks are out of control!
const observer = new MutationObserver((mutationsList, observer) => {
  for (const mutation of mutationsList) {
    if (mutation.attributeName === 'class') {
      if (! document.documentElement.classList.contains(hn)) {
        addClassToDamnedRootElement();
      }
    }
  }
});

observer.observe(document.documentElement, {
  attributes: true,
  childList: false,
  subtree: false
});

Create a new userscript and copy-paste that into it. Now you can safety do small style edits on various sites all within one userscript file. Every site will have a class on the root like example-com which you can easily target individually should you need to do that. Sites with subdomains can also be targeted like html.example-com.en, though only the one closest to the domain will be added.

Leave a comment

Your email address will not be published. Required fields are marked *