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
.
The positive lookahead construct is a pair of parentheses, with the opening parenthesis followed by a question mark and an equals sign. You can use any regular expression inside the lookahead (but not lookbehind, as explained below). Any valid regular expression can be used inside the lookahead.
Lookahead is used as an assertion in Python regular expressions to determine success or failure whether the pattern is ahead i.e to the right of the parser's current position. They don't match anything. Hence, they are called as zero-width assertions.
Negative lookahead That's a number \d+ , NOT followed by € . For that, a negative lookahead can be applied. The syntax is: X(?! Y) , it means "search X , but only if not followed by Y ".
Save this answer. Show activity on this post. grep in macOS does not support lookahead. For more information about the regex syntax supported in the default macOS binaries, see re_format(7).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With