So the CSS specificity rules dictate that ids are the most powerful, then classes, then tag names and then *.
So #id
> .class
> div
> *
.
What I'm trying to do is get a 'rating' for each if I provide a string of CSS selectors.
Say I have a Specificity array = [#id, .class, tagname]
span
should return [0, 0, 1]
body p
should return [0, 0, 2]
.red .orange
should return [0, 2, 0]
menu .item #checkout.active
should return [1, 2, 1]
I've tried this code, but something is definitely off:
function compare(a) {
const comparisonOperators = ["#", ".", " "];
const aRating = [];
for (let x = 0; x < comparisonOperators.length; x++) {
aRating[x] = a.includes(comparisonOperators[x])
? a.split(comparisonOperators[x]).filter((x) => x).length
: 0;
}
console.log(aRating);
}
compare("menu .item #checkout.active");
// returns [2,3,3]
Any thoughts on this?