Selectors
Parsec’s selector engine lives in parsec::css (crates/parsec/src/css.rs). It parses selectors from Selectors Level 4 once, into a SelectorList, and matches them right to left against a document.
The rule for what matches is simple to state: what a browser would match on the same page if nobody were looking at it. No pointer is hovering, nothing has focus, no link has been visited, and there’s no URL unless you pass one. Everything a static page can decide from its markup should match; what it can’t decide never matches. Where Parsec doesn’t match something it could, that’s a gap with an issue, listed below.
This page lists every selector Parsec parses, from the parser and from crates/parsec/tests/css.rs, and puts Lexbor’s behaviour beside it, read from Lexbor’s selectors.c at commit 145872a.
The API
Section titled “The API”SelectorList::parse
Section titled “SelectorList::parse”pub fn parse(selector: &str) -> Result<SelectorList, SelectorError>Parses a comma-separated list of complex selectors. An element matches the list if it matches any of them. Errors are listed under What’s refused. A SelectorList is Debug and Clone, holds no reference to any document, and can be kept and reused on as many documents as you like.
SelectorList::select
Section titled “SelectorList::select”pub fn select(&self, doc: &Document, scope: NodeId) -> Vec<NodeId>Every element under scope that matches, in document order.
scopeitself is never in the result, only its descendants.scopecan be any node: the document, an element, a fragment root, or a template’s contents node.- Combinators look past
scope, asquerySelectorAlldoes:div lirun on a<ul>finds thelis inside it when adivis above the<ul>. To pin a selector to the scope, start it with:scope. :scopeisscopewhen it’s an element. When it’s a document or fragment node,:scopemeans the same as:root.- It doesn’t look inside template contents, which aren’t under their template. Run it on
template_contents(id), or calladopt_template_contentsfirst. - It visits every node under
scopeand returns them all. To stop early, useselect_iterorselect_first.
SelectorList::select_iter and select_first
Section titled “SelectorList::select_iter and select_first”pub fn select_iter<'a>(&'a self, doc: &'a Document, scope: NodeId) -> Select<'a>pub fn select_first(&self, doc: &Document, scope: NodeId) -> Option<NodeId>The same matches as select, in the same order, found as you ask for them. select_iter returns Select, an Iterator<Item = NodeId> that walks only as far as you read it, so .take(10) on a huge page stops after the tenth match. select_first is the first match, or None, and doesn’t look past it.
use parsec::css::SelectorList;
let doc = parsec::parse("<ul><li>1</li><li>2</li><li>3</li></ul>", false);let li = SelectorList::parse("li").unwrap();
let first = li.select_first(&doc, doc.root()).unwrap();assert_eq!(doc.text(first), "1");
let two: Vec<String> = li.select_iter(&doc, doc.root()).take(2).map(|n| doc.text(n)).collect();assert_eq!(two, ["1", "2"]);
assert_eq!(SelectorList::parse("table").unwrap().select_first(&doc, doc.root()), None);SelectorList::specificity
Section titled “SelectorList::specificity”pub fn specificity(&self) -> (u32, u32, u32)Selectors 4’s specificity as (IDs, classes, types). For a list, it’s the most specific selector in it, which is also how :is() counts.
#idcounts an ID; a class, an attribute selector or a pseudo-class counts a class; a type selector counts a type;*counts nothing.:is(),:not()and:has()count as their most specific argument,:nth-child(An+B of S)as a class plus S, and:where()as nothing.- One mismatch with the spec:
|x, which matches nothing anyway, counts a class it shouldn’t.
use parsec::css::SelectorList;
let spec = |s: &str| SelectorList::parse(s).unwrap().specificity();assert_eq!(spec("ul li.item[data-id]"), (0, 2, 2));assert_eq!(spec("#main > a:hover"), (1, 1, 1));assert_eq!(spec("a, #x, .y"), (1, 0, 0));assert_eq!(spec(":is(#x, .y) p"), (1, 0, 1));assert_eq!(spec(":where(#x, .y) p"), (0, 0, 1));assert_eq!(spec("li:nth-child(2n of .item)"), (0, 2, 1));SelectorList::matches
Section titled “SelectorList::matches”pub fn matches(&self, doc: &Document, el: NodeId, scope: Option<NodeId>) -> boolWhether el matches, with scope as :scope. None makes :scope the root element. It’s false for anything that isn’t an element.
select_with, matches_with and MatchOptions
Section titled “select_with, matches_with and MatchOptions”pub fn select_with(&self, doc: &Document, scope: NodeId, options: &MatchOptions<'_>) -> Vec<NodeId>pub fn matches_with(&self, doc: &Document, el: NodeId, scope: Option<NodeId>, options: &MatchOptions<'_>) -> boolpub fn try_select_with(&self, doc: &Document, scope: NodeId, options: &MatchOptions<'_>) -> Result<Vec<NodeId>, MatchTimeout>pub fn try_matches_with(&self, doc: &Document, el: NodeId, scope: Option<NodeId>, options: &MatchOptions<'_>) -> Result<bool, MatchTimeout>
#[derive(Debug, Clone, Copy, Default)]pub struct MatchOptions<'a> { pub url: Option<&'a str>, pub budget: Option<Duration>, pub max_steps: Option<u64>,}select and matches with what the document can’t tell you on its own: url, the page’s address, which :target, :target-within and :local-link need (Given the page’s URL). MatchOptions::default() has no URL, and then select_with and matches_with give exactly what select and matches do.
The other two fields are limits, and only the try_ calls read them. max_steps stops after that many compounds matched; it needs no clock, so it works on wasm32 and gives the same answer on any machine. budget stops after that long, with the clock read every 1,024 compounds. Past either you get Err(MatchTimeout), never the matches found so far. Each binding takes them too:
| Call | Limits | Past one | |
|---|---|---|---|
| C | parsec_select_with, parsec_matches_with |
max_steps, budget_us |
PARSEC_ERR_TIMEOUT (C API) |
| Python | css(), css_first(), css_matches(), any_css_matches() |
max_steps=, budget= (seconds) |
TimeoutError (Python) |
| JavaScript | select, selectFirst, matches |
{ maxSteps } |
an Error (WASM) |
SelectorError
Section titled “SelectorError”#[derive(Debug, Clone, PartialEq, Eq)]pub struct SelectorError { pub reason: String,}Why a selector didn’t parse, in words: ":nope isn't supported", "a pseudo-element must end the selector", "an attribute selector without its ]". It implements Display (the reason) and std::error::Error. The wording is for people; don’t match on it.
use parsec::css::SelectorList;
let doc = parsec::parse( "<div><ul><li class=a>1</li><li class=b>2</li></ul></div>", false,);let ul = SelectorList::parse("ul").unwrap().select(&doc, doc.root())[0];
// Combinators look past the scope...let past = SelectorList::parse("div li").unwrap();assert_eq!(past.select(&doc, ul).len(), 2);
// ...unless you anchor to it.let direct = SelectorList::parse(":scope > li.b").unwrap();let found = direct.select(&doc, ul);assert_eq!(doc.text(found[0]), "2");
// The scope itself is never a result.assert!(SelectorList::parse("ul").unwrap().select(&doc, ul).is_empty());
// matches() tests one element.assert!(direct.matches(&doc, found[0], Some(ul)));assert!(!direct.matches(&doc, found[0], None));
let err = SelectorList::parse("a:nope").unwrap_err();assert_eq!(err.reason, ":nope isn't supported");Syntax
Section titled “Syntax”- Lists:
a, b. An empty list, an empty entry (a,,b), a leading comma (, a) and a trailing one (a,) are errors. - Combinators: descendant (whitespace), child
>, next-sibling+, subsequent-sibling~. The column combinator||,col || td, finds the cells under a<col>by the table model (see:nth-col()below). - Whitespace is space, tab, line feed, carriage return and form feed.
- Comments
/* ... */are skipped, but treated as whitespace, soa/**/.breads asa .brather thana.b. - Escapes work in names and strings:
#a\:b,.w-1\/2,#\39 lives. A hex escape takes up to six digits and one following whitespace character; zero, surrogates and values past U+10FFFF become U+FFFD. A backslash before a newline is an error in a name; in a string it continues the line. - Strings in attribute values take
"or'. A newline inside one is an error; one left open at the end of the selector is accepted. - Case: pseudo-class names,
odd,even,of,nand the attribute flags are ASCII case-insensitive (:NTH-CHILD(ODD)is fine).
Simple selectors
Section titled “Simple selectors”| Selector | Matches | Lexbor |
|---|---|---|
E |
Elements named E. HTML elements compare in any case; SVG and MathML elements compare exactly (clipPath, not clippath), as in a browser. See XML elements for Ns::Xml. |
Matches |
* |
Every element. | Matches |
*|E, *|* |
E (or anything) in any namespace. |
Matches |
|E, |* |
Elements in no namespace. Every element the HTML parser makes has one, so these never match. | Matches |
ns|E |
Refused: there’s no @namespace to declare ns with (#17). |
Not checked |
#id |
Elements whose id attribute is exactly id; without case in a Quirks::Quirks document. |
Matches |
.c |
Elements whose class, split on ASCII whitespace, contains c; without case in a Quirks::Quirks document. |
Matches |
use parsec::css::SelectorList;
let count = |html: &str, css: &str| { let doc = parsec::parse(html, false); SelectorList::parse(css).unwrap().select(&doc, doc.root()).len()};let page = "<!DOCTYPE html><div id=X class='Wide page'><svg><clipPath/></svg></div>";assert_eq!(count(page, "DIV"), 1);assert_eq!(count(page, "clipPath"), 1);assert_eq!(count(page, "clippath"), 0);assert_eq!(count(page, ".Wide"), 1);assert_eq!(count(page, ".wide"), 0);assert_eq!(count(page, "#x"), 0);
// Without a doctype the page is in quirks mode: ids and classes ignore case.let quirky = "<div id=X class=Y></div>";assert_eq!(count(quirky, "#x"), 1);assert_eq!(count(quirky, ".y"), 1);Attribute selectors
Section titled “Attribute selectors”| Selector | Matches |
|---|---|
[a] |
Has an attribute a. |
[a=v] |
Value is exactly v. |
[a~=v] |
Value, split on whitespace, contains v. Never matches if v is empty or contains whitespace. |
[a|=v] |
Value is v, or starts with v-. |
[a^=v] |
Value starts with v. Never matches if v is empty. |
[a$=v] |
Value ends with v. Never matches if v is empty. |
[a*=v] |
Value contains v. Never matches if v is empty. |
[a=v i] |
Compares the value without ASCII case. |
[a=v s] |
Compares the value with case, even for the attributes HTML lists as case-insensitive. |
[*|a] |
An attribute with local name a in any namespace, or none: xlink:href matches [*|href]. |
[|a] |
An attribute a in no namespace, the same as [a]. |
Lexbor has all of these.
The value is a quoted string or an identifier: [data-id="17"] and [lang=en] work, [data-id=17] is an error because 17 isn’t an identifier, as in CSS. Any flag other than i or s is an error, and so is a namespace prefix on the name ([xlink|href]).
How names and values compare:
- On HTML elements the name compares without case (
[HREF]findshref). On SVG and MathML elements it compares with the case the spec gives the attribute, so[viewBox]matches and[viewbox]doesn’t, as in a browser. - A plain name means an attribute in no namespace. SVG’s
xlink:hrefis in the XLink namespace, so[href]doesn’t find it and[*|href]does. - Values compare with case, except on HTML elements for the 46 attributes the HTML Standard lists as case-insensitive in selectors,
typeandlangamong them. Thesflag turns that off;iturns it on for any attribute.
All 46 case-insensitive attributes
accept, accept-charset, align, alink, axis, bgcolor, charset, checked, clear, codetype, color, compact, declare, defer, dir, direction, disabled, enctype, face, frame, hreflang, http-equiv, lang, language, link, media, method, multiple, nohref, noresize, noshade, nowrap, readonly, rel, rev, rules, scope, scrolling, selected, shape, target, text, type, valign, valuetype and vlink.
use parsec::css::SelectorList;
let doc = parsec::parse( r##"<input type="TEXT"><a href="/p/1" hreflang="en-GB">a</a> <svg viewBox="0 0 1 1"><use xlink:href="#i"/><a href="b"></a></svg>"##, false,);let n = |css: &str| SelectorList::parse(css).unwrap().select(&doc, doc.root()).len();assert_eq!(n("input[type=text]"), 1); // type is on HTML's listassert_eq!(n("input[type=text s]"), 0);assert_eq!(n("[hreflang|=en]"), 1);assert_eq!(n("a[href^='/']"), 1);assert_eq!(n("[viewBox]"), 1);assert_eq!(n("[viewbox]"), 0);assert_eq!(n("[href]"), 2); // the HTML a and the SVG aassert_eq!(n("[*|href]"), 3); // plus use's xlink:hrefLogical pseudo-classes
Section titled “Logical pseudo-classes”| Selector | Matches | Lexbor |
|---|---|---|
:not(list) |
Elements that match none of the selectors in the list. The list takes complex selectors and isn’t forgiving: one bad entry makes the whole selector an error. | Matches |
:is(list) |
Elements that match any of them. The list is forgiving, as the spec says: entries that don’t parse are dropped, so :is(h1, ::nonsense, ) is :is(h1), and :is() is valid and matches nothing. |
Matches |
:where(list) |
The same elements as :is(), but it adds nothing to specificity. |
Matches |
:matches(list) |
An old name for :is(), accepted. |
Not checked |
:has(relative list) |
Elements with something related to them that matches. Each entry may start with >, + or ~; with none, it means a descendant. The list isn’t forgiving. |
Matches |
Unlike the spec and browsers, Parsec accepts :has() nested inside :has().
use parsec::css::SelectorList;
let doc = parsec::parse( r#"<ul><li class=first><a href="/1">A</a></li> <li class=sold><a href="/2">B</a><span class=price>2</span></li> <li><a href="https://x.example/3">C</a></li></ul>"#, false,);let n = |css: &str| SelectorList::parse(css).unwrap().select(&doc, doc.root()).len();assert_eq!(n("li:has(.price)"), 1);assert_eq!(n("li:has(> a[href^=http])"), 1);assert_eq!(n("li:has(+ li.sold)"), 1);assert_eq!(n("li:not(.sold, .first)"), 1);assert_eq!(n(":is(li.sold, span)"), 2);assert_eq!(n(":is(li, ::nonsense)"), 3);Tree-structural pseudo-classes
Section titled “Tree-structural pseudo-classes”Only elements count as siblings; text and comments between them don’t.
| Selector | Matches | Lexbor |
|---|---|---|
:root |
The element whose parent is the document node: <html>. Never matches in a fragment. |
Matches |
:scope |
The element a query runs from. See select for the rules. |
Parsed, never matches; support is an open pull request, lexbor#257 |
:empty |
Elements with no children but comments, processing instructions and empty text. A space counts as content. | Matches |
:first-child, :last-child, :only-child |
Position among element siblings. | Matches |
:first-of-type, :last-of-type, :only-of-type |
Position among siblings with the same namespace and name. | Matches |
:nth-child(An+B), :nth-last-child(An+B) |
The An+B-th child, counting from the start or end. | Matches |
:nth-child(An+B of S), :nth-last-child(An+B of S) |
Counting only siblings that match the selector list S. |
Matches |
:nth-of-type(An+B), :nth-last-of-type(An+B) |
Counting siblings of the same type. of S is an error here, as in the spec. |
Matches |
:nth-col(An+B), :nth-last-col(An+B) |
Table cells in the An+B-th column, from the start or the end. Columns come from the HTML table model, so colspan, rowspan (rowspan=0 too) and colgroup spans count, and a cell spanning several columns matches if any of them does. A table is laid out once per query, and stays linear however it’s built. |
Parsed, never matches |
:heading, :heading(1, 3) |
h1 to h6, of any level or of the levels listed, from the Selectors 5 draft. |
Not checked |
An+B accepts odd, even, an integer, and An+B forms such as n, -n+2, 2n + 1 and 3n-1. A and B must fit in an i32. Parsec is looser than CSS about spaces: 2 n and + 5 are accepted where a browser would refuse them. :nth-child(0) is valid and matches nothing.
use parsec::css::SelectorList;
let doc = parsec::parse( "<ul><li>1</li><li class=x>2</li><li>3</li><li class=x>4</li></ul><p></p><p> </p><p><!--c--></p>", false,);let texts = |css: &str| -> Vec<String> { SelectorList::parse(css).unwrap().select(&doc, doc.root()) .into_iter().map(|n| doc.text(n)).collect()};assert_eq!(texts("li:nth-child(odd)"), ["1", "3"]);assert_eq!(texts("li:nth-child(-n+2)"), ["1", "2"]);assert_eq!(texts("li:nth-last-child(1)"), ["4"]);assert_eq!(texts("li:nth-child(2 of .x)"), ["4"]);assert_eq!(texts("p:empty").len(), 2);assert_eq!(texts(":root").len(), 1);Link, form and editing pseudo-classes
Section titled “Link, form and editing pseudo-classes”These follow the HTML Standard’s definitions, read from attributes, because the attributes are all a static page has. Only HTML elements can match them.
The link, form and editing pseudo-classes, with the exact rules
| Selector | Matches | Lexbor |
|---|---|---|
:any-link, :link |
HTML’s <a> and <area> with an href. With nothing visited, every link is unvisited, so :link is the same as :any-link. SVG’s <a>, with href or xlink:href, doesn’t match yet, though in a browser it’s a link. |
Matches |
:checked |
<input type=checkbox> and <input type=radio> (type in any case) with a checked attribute, and <option> with a selected attribute. An option that’s selected only because it’s first in its <select> doesn’t match. |
Matches |
:disabled |
The spec’s “actually disabled”: a button, input, select, textarea or fieldset with disabled, or inside a <fieldset disabled> but not inside that fieldset’s first <legend>; an optgroup with disabled; an option with disabled or inside an <optgroup disabled>. |
Matches |
:enabled |
A button, input, select, textarea, optgroup, option or fieldset that isn’t disabled. |
Matches |
:required |
An input, select or textarea with required. |
Matches |
:optional |
An input, select or textarea without required. |
Matches |
:read-write |
An input whose type is text-like (text, search, url, tel, email, password, date, month, week, time, datetime-local, number, or missing) and that is neither readonly nor disabled; a textarea that is neither; any other element inside a contenteditable that isn’t "false". |
Matches |
:read-only |
Every element that isn’t :read-write. |
Matches |
:placeholder-shown |
An input with placeholder and an empty or missing value; a textarea with placeholder and no text. |
Matches |
:blank |
The current Selectors draft’s: an input a person types text into (text, search, url, tel, email, password or number) with no value, or a textarea with no text. |
Matches elements Lexbor counts as empty (selectors.c) |
:defined |
Everything but an HTML element with a custom element’s name, or with is=: a parsed page defines no custom elements. |
Not checked |
use parsec::css::SelectorList;
let doc = parsec::parse( r#"<form><fieldset disabled><legend><input name=in-legend></legend><input name=off></fieldset> <input type=checkbox checked name=box><input type=TEXT required readonly name=ro> <textarea placeholder=say></textarea></form>"#, false,);let names = |css: &str| -> Vec<String> { SelectorList::parse(css).unwrap().select(&doc, doc.root()).into_iter() .filter_map(|n| doc.attrs(n).find(|a| a.1 == "name").map(|a| a.2.to_string())) .collect()};assert_eq!(names("input:disabled"), ["off"]);assert_eq!(names(":checked"), ["box"]);assert_eq!(names(":required"), ["ro"]);assert_eq!(names("input:read-only"), ["off", "box", "ro"]);assert_eq!(SelectorList::parse(":placeholder-shown").unwrap().select(&doc, doc.root()).len(), 1);Form validity and defaults
Section titled “Form validity and defaults”These read the controls’ attributes as the HTML Standard’s definitions say, with the markup standing in for whatever a user would type: a control’s value is its value attribute, or a <textarea>’s text. Only HTML elements match.
The form pseudo-classes, with the exact rules
| Selector | Matches | Lexbor |
|---|---|---|
:default |
A checkbox or radio button with checked; an <option> with selected; and a form’s default button, which is the first submit button (a <button> whose type isn’t reset or button, or an <input type=submit> or type=image) in tree order that belongs to the same form. A button belongs to the form its form attribute names, or else to the nearest <form> around it; a button with no form is nobody’s default. |
Parsed, never matches |
:indeterminate |
A radio button with no checked whose group has nothing checked. The group is the radio buttons with the same name and form owner; with no name, the button is a group of one. Also a <progress> with no value. A checkbox never matches, because only a script can make one indeterminate. |
Parsed, never matches |
:in-range, :out-of-range |
An <input> of type number, date, month, week, time, datetime-local or range that has a min or max it can read (a range input always has both: 0 and 100 unless it says otherwise), and isn’t barred from validation. The type attribute has to be there: an <input> with none matches neither. It’s out of range when its value is below min or above max. A time input whose min is later than its max wraps past midnight, so 22:00 to 06:00 holds 23:00. An empty or unreadable value is in range, and a range input always is, since its value is pulled into range. |
Parsed, never matches |
:valid, :invalid |
Whether a control meets its constraints (below). A <form> is invalid when any control it owns is, and a <fieldset> when any control inside it is. |
Parsed, never matches |
A control is barred from validation, and then matches neither :valid nor :invalid nor the range pair, when it’s disabled (as :disabled reads it), inside a <datalist>, readonly on a type where that applies (a <textarea>, or an <input> that :read-write counts as text-like), or an <input> of type hidden, reset or button. A <button> that submits is always valid; any other <button>, and every element that isn’t a control, matches neither.
What :valid checks, for the rest:
required. A text-like input or<textarea>with an empty value, a checkbox withoutchecked, a required radio group with nothing checked, and a required file input (a static page has no files chosen) are invalid. A required<select>is invalid when nothing it would submit is selected: no option markedselectedin a multiple select or a list box (sizeover 1), or in a one-line select the placeholder: a first option with an empty value that’s a direct child of the<select>.- The value’s type.
emailneeds a valid email address, or withmultiplea comma-separated list of them;urlneeds an absolute URL that parses.number,date,month,week,timeanddatetime-localdrop a value that isn’t valid for the type, as the HTML Standard’s value sanitization does, and then count it as empty. Line breaks are taken out first, andurlandemailvalues are trimmed. minandmax, as for:out-of-range, andstep. A value off the step fromminis invalid.step="any"turns the check off, and so does aminthat can’t be read. A missing or badstepmeans 1 (a day, a month, a week, or fortimeanddatetime-local60 seconds).pattern, ontext,search,tel,url,emailandpasswordinputs with a value, and on each address of a multipleemail. The pattern is JavaScript’s regular expression syntax, compiled with thevflag and anchored to the whole value, as the HTML Standard says: case-sensitive,.stops at line breaks, and^and$are the ends of the value. A pattern that doesn’t compile counts as no pattern. Unicode property escapes work, sopattern="\p{L}+"on a name field does what it says: General_Category, Script and Script_Extensions by any of their names, and every binary property ECMAScript lists, from Unicode 17.0 tables built into the crate. The one gap is thevflag’s properties of strings, such as\p{RGI_Emoji}, which still count as no pattern. Lookbehind is matched forwards from each earlier position rather than backwards, which only changes what a capture inside one holds.- What only typing can cause, too long, too short and bad input, isn’t checked.
use parsec::css::SelectorList;
let doc = parsec::parse( r#"<form id=f> <input name=zip pattern="[0-9]{5}" value="1234"> <input name=qty type=number min=1 max=10 value=12> <input name=mail type=email required value="[email protected]"> <input type=radio name=size value=s><input type=radio name=size value=m> <button>Send</button><button>Other</button> </form> <progress></progress>"#, false,);let n = |css: &str| SelectorList::parse(css).unwrap().select(&doc, doc.root()).len();let names = |css: &str| -> Vec<String> { SelectorList::parse(css).unwrap().select(&doc, doc.root()).into_iter() .filter_map(|n| doc.attrs(n).find(|a| a.1 == "name").map(|a| a.2.to_string())) .collect()};assert_eq!(names("input:invalid"), ["zip", "qty"]);assert_eq!(names("input:out-of-range"), ["qty"]);assert_eq!(n("form:invalid"), 1);assert_eq!(n(":indeterminate"), 3); // both radios and the <progress>assert_eq!(n("button:default"), 1); // only the first submit buttonLanguage and direction
Section titled “Language and direction”| Selector | Matches | Lexbor |
|---|---|---|
:lang(range, ...) |
Elements whose language matches any of the ranges. The language is the nearest xml:lang or lang on the element or an ancestor, xml:lang first when one element has both. Ranges match by RFC 4647’s extended filtering, as Selectors 4 says, without case: de matches de-CH, de-CH matches de-Latn-CH, and a quoted '*-CH' matches any tag with the region CH. A missing subtag matches anything, but never past a one-letter one, so de-CH doesn’t match de-x-CH. :lang() with no range is an error. |
Parsed, never matches |
:dir(ltr), :dir(rtl) |
Elements whose direction is left to right, or right to left, by the HTML Standard’s rules as far as the markup decides them. Any other identifier parses, as the Selectors draft says, and never matches. | Parsed, never matches |
How :dir() works out an element’s direction:
dir="ltr"anddir="rtl", in any case, decide it. Any other value is ignored, and so isdiron an SVG or MathML element.- With no
dirof its own, an element takes its parent’s direction. At the top, it’s left to right. dir="auto", and a<bdi>without a validdir, take the direction of the first strong character in their text. Text inside a<bdi>,<script>,<style>or<textarea>, or inside an element with its own validdir, is left out. No strong character means left to right.- On a
<textarea>,dir="auto"reads its text. On an<input>of typetext,search,tel,urloremail(or no type), it reads thevalueattribute. Any other<input>is left to right.
use parsec::css::SelectorList;
let doc = parsec::parse( r#"<div lang="de-CH"><p id=a>Grüezi</p></div><p id=b lang="en-GB">Hello</p> <div dir="rtl"><span id=c>שלום</span></div> <p id=d dir="auto">123 مرحبا</p><p id=e dir="auto">123</p>"#, false,);let ids = |css: &str| -> Vec<String> { SelectorList::parse(css).unwrap().select(&doc, doc.root()).into_iter() .filter_map(|n| doc.attrs(n).find(|a| a.1 == "id").map(|a| a.2.to_string())) .collect()};assert_eq!(ids(":lang(de)"), ["a"]);assert_eq!(ids(":lang(en, fr)"), ["b"]);assert_eq!(ids("p:lang('*-CH')"), ["a"]);assert_eq!(ids(":dir(rtl)"), ["c", "d"]); // the div matches too, but has no idassert_eq!(ids("p:dir(ltr)"), ["a", "b", "e"]);Given the page’s URL
Section titled “Given the page’s URL”A page doesn’t know its own address, so these need you to tell them. Pass it in MatchOptions to select_with or matches_with. Without a URL, or with one that doesn’t parse, they match nothing, which is what select and matches give.
| Selector | Matches, given a URL | Lexbor |
|---|---|---|
:target |
The element the URL’s fragment points at, as the HTML Standard finds it: the first element whose id is the fragment, else the first <a> whose name is; tried as written, then percent-decoded, so #caf%C3%A9 finds id="café". The comparison keeps case. An empty fragment, or one that names nothing, gives no target. |
Never matches |
:target-within |
The target and every element it’s inside. | Never matches |
:local-link |
<a> and <area> whose href points at the page itself: resolved against the URL (or the first <base href>), it’s the same URL apart from the fragment. The query string counts. |
Never matches |
use parsec::css::{MatchOptions, SelectorList};
let doc = parsec::parse( r##"<nav><a href="#prices">Prices</a><a href="/shop/list?page=2">Next</a><a href="https://x.example/">Elsewhere</a></nav> <section id="prices"><h2>Prices</h2></section>"##, false,);let at = MatchOptions { url: Some("https://shop.example/shop/list?page=2#prices"), ..Default::default() };
let target = SelectorList::parse(":target").unwrap();let found = target.select_with(&doc, doc.root(), &at);assert_eq!(doc.lower_name(found[0]), Some("section"));
let local = SelectorList::parse(":local-link").unwrap();assert_eq!(local.select_with(&doc, doc.root(), &at).len(), 2);
// Without the URL there's nothing to compare with.assert!(target.select(&doc, doc.root()).is_empty());assert!(!target.matches(&doc, found[0], None));assert!(target.matches_with(&doc, found[0], None, &at));The URL is parsed with the url crate for now. Parsec’s own WHATWG URL parser will take its place when it lands (#26).
Parsed, but never match
Section titled “Parsed, but never match”These parse, so a stylesheet’s selectors don’t fail on them, and always give false. Each one is about a state a page nobody’s using can’t be in.
| Selector | Why it never matches | Lexbor |
|---|---|---|
:hover, :active, :focus |
Nothing is hovered, pressed or focused. | Matches elements that have an attribute of the same name: active, focus, hover |
:focus-visible, :focus-within |
Nothing has focus. | Never matches |
:visited |
Nothing has been visited. | Never matches |
:user-valid, :user-invalid |
They depend on the user having interacted with the control. | :user-invalid never matches |
What’s refused
Section titled “What’s refused”Everything not listed above is an error from SelectorList::parse. Some of these Lexbor parses and never matches; Parsec refuses them for now, so a query can’t silently find nothing.
Everything that's refused, and what Lexbor does with it
| Selector | Status | Lexbor |
|---|---|---|
A pseudo-element anywhere but the end, ::before a, or an unknown one, ::nope |
Refused. Known pseudo-elements (::before, ::after, ::marker, ::part(), ::slotted() and the rest, and the legacy :before, :after, :first-line and :first-letter) parse, as querySelector has them, and match nothing, since they aren’t elements. |
Parsed, never match |
A namespace prefix such as svg|rect that isn’t declared |
Refused. Declare prefixes, and a default namespace, with SelectorList::parse_with and ParseOptions, as @namespace rules would; *| and | need no declaring. |
Not supported |
:current, :past, :future, :fullscreen, :host, :open, :modal, :popover-open and other pseudo-classes not on this page |
Refused. | :current, :past, :future, :fullscreen parsed, never match |
:lexbor-contains() |
Refused; it’s Lexbor’s own extension. Filter on text instead. |
Matches |
[a!=b], an unknown attribute flag, an unquoted value that isn’t an identifier |
Refused. | Not checked |
Lexbor’s column is from its matcher, selectors.c; “Not checked” means we haven’t looked. One open Lexbor matching bug is worth knowing if you’re comparing results: ~ after :is() or :where() only looks at the next sibling (lexbor#436).
use parsec::css::SelectorList;
for bad in ["", "a,", "::before a", "::nope", "svg|rect", ":nope", "[a!=b]", "[a=b x]"] { assert!(SelectorList::parse(bad).is_err(), "{bad:?} parsed");}for never in [":hover", ":visited", ":focus-within", ":user-invalid", "a::before", ":dir(up)"] { let doc = parsec::parse("<a href=x>x</a>", false); assert!(SelectorList::parse(never).unwrap().select(&doc, doc.root()).is_empty());}XML elements
Section titled “XML elements”Elements created with Ns::Xml (Parsec’s HTML parser never makes them) match as Netweir’s XML support needs:
- A type selector names the local part, in any case:
creatormatchesdc:creatorandCreator. - An attribute selector finds the attribute by its local name in any case, preferring one written exactly as asked:
[id=lo]looks atidbeforeID, and only that one attribute is compared. Values compare with case unless you addi. #idand.classcompare exactly, using the attribute named exactlyidorclass.
The nesting limit
Section titled “The nesting limit”Parsing and matching both recurse once for each functional pseudo-class inside another (:not, :is, :where, :matches, :has and the :nth-* family, including an of S list). To keep a hostile selector from overflowing the stack, nesting stops at 32 levels. The 33rd is an error: selectors nest more than 32 deep. Inside a forgiving :is() or :where(), the part that’s too deep is dropped like any other bad entry, so the selector parses and that branch matches nothing.
use parsec::css::SelectorList;
let ok = format!("{}a{}", ":not(".repeat(32), ")".repeat(32));assert!(SelectorList::parse(&ok).is_ok());let deep = format!("{}a{}", ":not(".repeat(33), ")".repeat(33));assert_eq!(SelectorList::parse(&deep).unwrap_err().reason, "selectors nest more than 32 deep");Matching runs right to left: for each element, the rightmost compound first, then the combinators outward. A few things cost more than they look:
selectwalks every node under the scope.- A descendant combinator tries each ancestor in turn, and long chains such as
div div div pon a deep page retry the same ancestors; there’s no caching between attempts. :has()searches the subtree (or the following siblings and their subtrees) of every element it’s tested on.- An attribute selector reads every attribute of every element it’s tested on.
- With a URL,
select_withandmatches_withfirst parse it and walk the document once to find the target and any<base>. That’s once per call: for many elements, oneselect_withcosts less thanmatches_withon each. :dir()walks up to the nearestdir, anddir="auto"reads text until the first strong character.
One case is still quadratic: a :has() of more than one compound that matches nothing below a deep anchor. div:has(span div) over a few thousand nested divs costs depth squared for the first such anchor. If you run selectors or pages you don’t control, that’s what max_steps is for. A walk of the tree is a compound or so an element, and a few hundred million is seconds of work.
Against Lexbor, Parsec is ahead on every selector in the benchmark, 3.2 times as fast over all 32 (Benchmarks). Its narrowest leads are where the notes above say it repeats work: body *:last-child, nav ul li a and [class], at 1.1 to 1.2 times.
See also
Section titled “See also”- The document tree, for reading the nodes a query returns.
- Moving from Lexbor, for the differences in one list.
- Limits and hostile input, for the other limits Parsec keeps.