11

I know in Perl regex the notion of the positive lookahead ie q(?=u) matches a q that is followed by a u, without making the u part of the match. I'm looking for something similar in css: I want to match a div, followed by a sibling div.specialClass.

<div>..</div>  <!-- div to match -->
<div class="specialClass">..</div>

I've played around with + but that matches with div.specialClass, whereas I want the preceding div.

dr jerry
  • 9,768
  • 24
  • 79
  • 122

2 Answers2

10

You cannot yet declare which part of the selector is the subject. The subject is always the last element of the selector in CSS, until we get the power to move that, likely using the $ or ! syntax.

// Always selects the .specialClass div which follows another div
div + div.specialClass {
    color: red;
}

In the future, you'll be able to make the first div the subject, likely with the following syntax:

// Selects any `div` preceding any `div.specialClass`
$div + div.specialClass { // or maybe div! + div.specialClass
    color: red;
}

Your only workaround in the interim is to use JavaScript. A tool like jQuery would make this very trivial:

$("div + div.specialClass").prev();

Which is now a reference to all div elements immediately preceding any div.specialClass.

Demo: http://jsfiddle.net/jonathansampson/HLfCr/
Source: http://dev.w3.org/csswg/selectors4/#subject

Sampson
  • 265,109
  • 74
  • 539
  • 565
  • Cool, is there an RFC for this? – Paul Jun 02 '12 at 19:34
  • @Jonathan Sampson Thanks for answer. Is there still a chance to vote/propose for the regex syntax: `div ?= div.specialClass ? (I love regex) – dr jerry Jun 02 '12 at 19:38
  • @drjerry You can speak your mind to the W3C I'm sure, however I think it's more likely they will go with `$` since that's what appears to be the standard in current working drafts of Level 4 Selectors. – Sampson Jun 02 '12 at 19:40
  • @Jonathan Sampson I will rest my case. Giving it a second thought $ as focus selector/operator is probably more intuitive. – dr jerry Jun 02 '12 at 19:43
  • 1
    @drjerry The `$` isn't set in stone yet. There's also `!`, which would follow the subject. I'm not sure what will be final. – Sampson Jun 02 '12 at 19:44
2

Keep an eye on the CSS4 selector :has() which has almost all browser support *sad Firefox noises*

div:has(+div.specialClass)

Thanks @porg for the update!

Jay Wick
  • 12,325
  • 10
  • 54
  • 78
  • 2
    **Update:** CSS `:has()` is meanwhile [more widely supported](https://caniuse.com/css-has)! And yes it is the conceptual equivalent to a RegEx lookahead. It selects an element if certain element(s) after it fulfill certain criteria, but does not select that lookahead part. – porg Jun 21 '23 at 15:16