How to get a list of CSS difference styles between two HTML elements with Javascript

About

This article shows you how to programmatically with Javascript get the styles property difference between two HTML element with Javascript

Steps

The script

The function that:

  • select the element with a selector (one for each)
  • onlyTextProp filters the layout properties: padding, margin, border, display
  • uses the window.getComputedStyle function.
let cssDiff = function (firstSelector, secondSelector, onlyTextProp = true) {

    let firstElement = document.querySelector(firstSelector);
    let firstElementStyles = window.getComputedStyle(firstElement);
    let firstElementTitle = firstElement.innerText.substr(0, 10);

    let secondElement = document.querySelector(secondSelector);
    let secondElementStyles = window.getComputedStyle(secondElement);
    let secondElementTitle = secondElement.innerText.substr(0, 10);

    let attributeName;
    let firstValue;
    let secondValue;
    //console.clear();
    console.log(`New Diff between ${firstElementTitle} and ${secondElementTitle}`)
    let sameCounter = 0;
    let diffCounter = 0;
    for (let i = 0; i < firstElementStyles.length; i++) {
        attributeName = firstElementStyles.item(i);
        if(onlyTextProp) {
            let isLayoutAttribute = attributeName.match(/^(margin|border|padding|display).*/m);
            if (isLayoutAttribute) {
                continue;
            }
        }
        firstValue = firstElementStyles.getPropertyValue(attributeName);
        secondValue = secondElementStyles.getPropertyValue(attributeName);
        if (firstValue !== secondValue) {
            console.log(`${attributeName}: ${firstValue} vs ${secondValue}`);
            diffCounter++;
        } else {
            sameCounter++;
        }
    }
    console.log("End Diff")
    console.log(`Total: ${firstElementStyles.length}`)
    console.log(`Same: ${sameCounter}`);
    console.log(`Diff: ${diffCounter}`);
}

Usage: demo

  • The two paragraph elements to compare
<p style="font-weight:bold">A paragraph element with bold</p>
<p>A basic paragraph element</p>
  • The javascript
let firstElementSelectors = "p";
let secondElementSelectors = "p:nth-child(2)";
cssDiff(firstElementSelectors, secondElementSelectors )
  • Output:





Discover More
Card Puncher Data Processing
Datacadamia - Data all the things

Computer science from a data perspective



Share this page:
Follow us:
Task Runner