Selecting the First Element Matching a Selector

CSS has pseudo-classes that allow you to select the first instance of a selector at any level in the DOM like :first-of-type(), but there is no equivalent in CSS for the ability to select only the first instance of an element matching a selector in the entire document (at any level). This would function more like document.querySelector() in JavaScript.

Parts Required

JS Tests

Using document.querySelector the ensure it’s the first instance:

this === document.querySelector(test)

Plugins Capable

Syntax Examples

EQCSS

@element strong {
  eval('document.querySelector("strong") === $it && "$this"') {
    background: lime;
  }
}

Selectory

strong[test='this === document.querySelector(`strong`)'] {
    background: lime;
  }
}

Demos