Reputation: 21486
Is there any way to find out if a css rule (a string) is applied to a particular 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]
There used be a special function in WebKit/Blink that returned all the matched rules for the element - window.getMatchedCSSRules(node)
- but it was deprecated and no longer works.
Is there any better way than looping through all the selectors and checking if they match the element? Also, this way still doesn't allow you to check for :hover state easily, etc.
Upvotes: 5
Views: 4113
Reputation: 272106
You can use document.querySelectorAll
to find all elements that match the rule, then check if the result contains the desired element:
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>
Upvotes: 7
Reputation: 1397
You can use Element.matches
|| Element.matchesSelector
Adapting MDN reference with 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;
}
Upvotes: 8
Reputation: 33399
You could use document.querySelectorAll(rule)
to get all elements that match your selector, and then check if your element is in there:
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;
}
Upvotes: 0