Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

positive lookahead in css

Tags:

regex

css

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.

like image 270
dr jerry Avatar asked Jun 02 '12 19:06

dr jerry


People also ask

What is positive lookahead?

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.

What is a lookahead in regex?

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.

Can I use negative lookahead?

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 ".

Does grep support lookahead?

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).


1 Answers

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

like image 78
Sampson Avatar answered Oct 21 '22 13:10

Sampson