Reputation: 2755
Is there a way do determine if a selector is currently been applied to an given element?
I know it´s possible to iterate over all CSS selectors, and test if each one is applicably or not. But I´m not sure if this is the way that Firebug and other inspector do it.
EDIT: I need a way to do it dynamically, with JS.
Upvotes: 3
Views: 217
Reputation: 179256
You can check if an element instance is matched by a selector by using document.querySelectorAll
and Array.prototype.indexOf
:
function elementMatchesSelector(element, selector) {
return Array.prototype.indexOf.call(document.querySelectorAll(selector), element) > -1;
}
Of course this only works for modern browsers that support the aforementioned methods.
Alternatively you can use Element.matches
:
function elementMatchesSelector(element, selector) {
var fn;
if (!element) {
return false;
}
fn = element.matches || element.mozMatchesSelector || element.msMatchesSelector || element.webkitMatchesSelector;
if (fn) {
return fn.call(element, selector);
}
return false;
}
Upvotes: 2
Reputation: 26203
In Firebug, you can look at the Computed Side Panel. For any given DOM element, it shows the CSS styles applied (even those applied via JavaScript). It also depicts the styles that were overridden. From the docs:
The Computed Side Panel shows all CSS style values calculated by the user agent while interpreting the given CSS information for the selected node inside the HTML Panel.
Upvotes: 1