Visualise CSS selectors like :read-only in debug (F12 tools)

573 Views Asked by At

Having

:read-only, [readonly] {
    background-color: aliceblue;
}
<form>
    <h2>test</h2>
</form>

How can I detect, when debugging, say, in Chrome, that the h2(or form) field has an :read-only property (or other type of selector, like :disabled, etc.) set to true?

PS.

To clarify the question: the question is not about a CSS workaround for this concrete case, but rather a way to identify for a concrete element in devtools (F12 tools) if that element has or not some selectors, :read-only was an example among others...

2

There are 2 best solutions below

1
On BEST ANSWER

In Chrome DevTools this is visible in the "Styles" pane on the "Elements" tab. For your specific example the output looks like this:

styles pane in elements tab - showing :read-only selector

Note that matching part of the selector (:read-only in this case) is in black letters, while part that doesn't match ([readonly]) is greyed out.


More general solution to the problem, that allows you to check if any selector matches any DOM node, is to use Element.matches(). Simply inspect any DOM node and in the console execute $0.matches(':some-selector') ($0 refers to last inspected element). This should work in all browsers.

calling $0.matches in the DevTools console

3
On

At least in Chrome:

  • :read-only selector applies to any noeditable elements (<h2> and <p> in snippet and <html> in your case)
  • [readonly] selector only applies to elements with readonly attribute (<p> in snippet)

So you can use readonly attribute and [readonly] selector

form :read-only {
    background-color: aliceblue;
}
form [readonly] {
    border: 1px dashed #d00;
}
<form>
  <h2>test</h2>
  <input type="text" />
  <p readonly="readonly">test2</p>
</form>