Don Steel
Don Steel

Reputation: 21

Get all class names of certain CSS attributes

Given a CSS attribute, e.g.

color: #fff;

how would I find all class names where this attribute is being applied?

For example,

.hello {
    color: #fff;
    background: blue;
}
.world {
    color: pink;
    background: teal;
}
.white,
.classname {
    color: #fff;
}

would return .hello, .white and .classname as they all have the attribute color: #fff.

Upvotes: 1

Views: 153

Answers (1)

Keith
Keith

Reputation: 24181

You can traverse the styleSheets, and then traverse the rules..

Here is an example..

It also includes a little utility function to convert the color, because inside the stylesheet #fff will be rgb(255, 255, 255)..

function realColor (name) {
  const d = document.createElement("div");
  d.style.color = name;
  d.style.display = "none";
  document.body.appendChild(d);
  const ret = window.getComputedStyle(d).color;
  d.remove();
  return ret;
}

const findcolor = realColor("#fff");

console.log("What selectors have a color of #fff?");
for (const s of document.styleSheets) {
  for (const r of s.cssRules) {
    if (r.style && r.style.color) {
      if (r.style.color === findcolor) {
        console.log(r.selectorText);
      }
    }
  }
}
.hello {
    color: #fff;
    background: blue;
}
.world {
    color: pink;
    background: teal;
}
.white,
.classname {
    color: #fff;
}
<span class="hello">hello</span>
<span class="world">world</span>

Upvotes: 1

Related Questions