JavaScript: check if a CSS rule applies to an element
Is there a way to find out if a CSS (string) rule applies to a specific element on the page? For example:
HTML:
<ul class="list">
<li>List item</li>
<li id="item">I want to check this element</li>
</ul>
CSS
.list > li { color: red; }
JS:
var item = document.getElementById('item');
var rule = '.list > li';
isRuleApplied(rule, item);
function isRuleApplied(rule, item) {
// ???
// returns true if rule matches the item, false otherwise
}
[Edit] WebKit / Blink used a special function that returned all the agreed rules for an element - window.getMatchedCSSRules(node)
but was deprecated and no longer works.
Is there a better way than to iterate over all the selectors and check if they match an element? Also, this way still doesn't allow you to check: easily hover state, etc.
source to share
You can use Element.matches
||Element.matchesSelector
Adapting MDN link from Polyfill (for cross-browser support):
function isRuleApplied(element,selector) {
if(typeof element.matches == 'function')
return element.matches(selector);
if(typeof element.matchesSelector == 'function')
return element.matchesSelector(selector);
var matches = (element.document || element.ownerDocument).querySelectorAll(selector);
var i = 0;
while (matches[i] && matches[i] !== element)
i++;
return matches[i] ? true : false;
}
source to share
You can use document.querySelectorAll
to find all elements that match a rule and then check if the result contains the element you want:
function isRuleApplied(rule, element) {
var elements = document.querySelectorAll(rule), i;
for (i = 0; i < elements.length; i++) {
if (elements[i] === element) {
return true;
}
}
return false;
}
console.log(isRuleApplied(".list > li", document.getElementById("item1"))); // true
console.log(isRuleApplied(".list > li", document.getElementById("item2"))); // false
<ul class="list">
<li id="item1">Match this</li>
</ul>
<ul class="test">
<li id="item2">But not this</li>
</ul>
source to share
You can use document.querySelectorAll(rule)
to get all the elements that match your selector and then check if your element is found:
function isRuleApplied(r, i) {
var all = document.querySelectorAll(rule);
for (var j = 0; j < all.length; j++) {
if (all[j] == i) {
return true;
}
}
return false;
}
source to share