Stylesheet Tools

by Scott Kaye

HTML

<div></div>
<div class="sticky"></div>
<div class="stickyWithTop"></div>

CSS

.sticky {
  position: sticky
}

.stickyWithTop {
  position: sticky;
  top: 20px;
}

JavaScript

class StylesheetTools {
  static NodeListContainsNode(list, node) {
    return [].some.call(list, n => {
      return node.isSameNode(n);
    });
  }

  static getStyles(node) {
    let styleDeclarations = [];
    let setProps = new Set();
    let computed = window.getComputedStyle(node);

    for (let sheet of document.styleSheets) {
      for (let rule of sheet.rules) {
        let matches = document.querySelectorAll(rule.selectorText);
        if (StylesheetTools.NodeListContainsNode(matches, node)) {
          styleDeclarations.push(rule.style);
        }
      }
    }

    // Get only set styles
    styleDeclarations.forEach(decl => {
      for (let style of decl) {
        setProps.add(style);
      }
    });

    let cssStyles = {};
    Array.from(setProps).map(prop => {
      cssStyles[prop] = computed[prop];
    });

    return cssStyles;
  }
  
  static getInitialValue(prop) {
  	let el = document.createElement("div");
    el.style[prop] = "initial";
    document.body.appendChild(el);
    let initial = window.getComputedStyle(el)[prop];
    document.body.removeChild(el);
    return initial;
  }
}

console.clear();
let sticky = document.querySelector("div.stickyWithTop");
console.log("styles:", StylesheetTools.getStyles(sticky));
console.log("initial value for top:", StylesheetTools.getInitialValue("top"))