Last Updated:

How do I test CSS selectors in JavaScript?

There are many ways to check if your CSS code will work in the browser. If you want to check if a particular property is supported, use a directive like this:@supports

@supports (display: grid) {
  div {
    display: grid;
  }
}

If the browser supports the property , it will use the styles from this directive, otherwise it will simply ignore the entire block of code.display:grid

If you want to test an entire selector, use the feature that browsers support surprisingly well.@supports selector()

@supports selector(:nth-child(1 of .class)) {
  /* Сделать что-то */
}
@supports selector()

If you want to know more, Chris Coyer wrote a good note about .@supports selector()

In the current project, I found myself in a situation where I needed to test support for the relatively new :where() selector. It's not an easy situation: and , and appeared in browsers around the same time, so if you want to check in this way whether the selector is supported by older browsers like Safari 13, then nothing will work. And I needed a normal solution for older browsers, so I started looking for alternatives and eventually decided to use JavaScript.:where()@supports selector()

I found this solution in Lea Veru's post. In 2011, she wrote about how to test CSS selector support by creating a new element with the right selector. After that, we check whether the rule appears in the style sheet. This is a good move even for browsers older than IE8.style

But Lea mentioned a simpler way: use in an expression with try... catch(). And given that the Selectors API is already working pretty well, I settled on this option. See for yourself:document.querySelector()

try {
    document.querySelector(selector)
} catch (error) {
    console.error(error)
}

The browser will try to execute the method with the selector we want to test. If the selector is not supported, the program will throw an exception and execute the code in the . In the example above, the error will be displayed in the console.document.querySelector()catch

Wrap this in a reusable function that will return if the selector is supported, or if not.truefalse

const isSelectorSupported = (selector) => {
    try {
        document.querySelector(selector)
        return true
    } catch (error) {
        return false
    }
}

You can now check the support for any selector and, for example, add a class directly to the element if the browser is ok.<html>

if (isSelectorSupported(":where(body)")) {
    document.documentElement.classList.add("supports-where")
}

I would recommend checking selector support using CSS only. But if for some reason this method does not suit you, use this small useful function.