简体   繁体   中英

Determine what CSS selectors are been applied to an element

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.

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;
}

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.

在此输入图像描述

那么使用getComputedStyle() MDN Link呢?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM