Skip to main content

Selector

Struct Selector 

Source
pub struct Selector { /* private fields */ }
Available on crate feature query only.
Expand description

A parsed, reusable CSS selector list.

Parse once, match many times: pass &selector anywhere a selector string is accepted (Dom::select, NodeRef::closest, …).

Supported: type, *, #id, .class, attribute selectors (=, ~=, |=, ^=, $=, *=, with i/ s flags), selector lists, all four combinators (descendant, >, +, ~), :first-child, :last-child, :only-child, :nth-child(An+B [of S]), :nth-last-child(), the *-of-type variants, :empty, :root, :scope, :not(), :is(), :where(), :has() (relative: :has(> img), :has(+ p)), :checked, :disabled, :enabled, CSS escapes (.md\:flex), and the non-standard jQuery-style :contains("text") (case-sensitive substring of the text content). Tag, attribute and pseudo-class names are ASCII case-insensitive; ids, classes and attribute values are case-sensitive, except the values of HTML’s enumerated attributes (type, method, dir, rel, …), which compare case-insensitively as in browsers unless the selector says s. Anything else (:hover, ::before, namespaces, …) is a parse error, never silently ignored.

Sibling combinators and positional pseudo-classes count elements only. Top-level nodes count as siblings of each other, so li + li works on a fragment like <li>a</li><li>b</li>; each top-level element is :root.

use domtree::Selector;

let dom = domtree::parse("<ul><li class='on'>a</li><li>b</li></ul>");
let sel = Selector::parse("li:not(.on)").unwrap();
let hits: Vec<_> = dom.select(&sel).map(|n| n.text_content()).collect();
assert_eq!(hits, ["b"]);

// `FromStr` works too.
let sel: Selector = "ul > li".parse().unwrap();
assert_eq!(dom.select(&sel).count(), 2);

Implementations§

Source§

impl Selector

Source

pub fn parse(selector: &str) -> Result<Selector, SelectorError>

Parse a selector list such as "ul > li.active, a[href^='https:']".

Anything outside the supported grammar is an error — including pseudo-classes this engine doesn’t implement (:hover, ::before, …), which are rejected rather than silently ignored.

use domtree::Selector;

assert!(Selector::parse("div > p:first-child").is_ok());

let err = Selector::parse("div > p)").unwrap_err();
assert_eq!(err.position(), 7);
assert_eq!(err.to_string(), "unexpected ')' at byte 7");
Source

pub fn matches(&self, node: NodeRef<'_>) -> bool

Whether node is an element matching this selector, evaluated against the whole document node belongs to.

use domtree::Selector;

let dom = domtree::parse("<div class='card'><h2>Title</h2></div>");
let h2 = dom.find_by_tag("h2").next().unwrap();
assert!(Selector::parse(".card > h2").unwrap().matches(h2));
assert!(!Selector::parse("h2:empty").unwrap().matches(h2));

Trait Implementations§

Source§

impl AsSelector for Selector

Source§

fn as_selector(&self) -> Option<Cow<'_, Selector>>

The parsed selector, or None if this is not a valid selector.
Source§

impl Clone for Selector

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Selector

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl FromStr for Selector

Same as Selector::parse.

Source§

type Err = SelectorError

The associated error which can be returned from parsing.
Source§

fn from_str(s: &str) -> Result<Selector, SelectorError>

Parses a string s to return a value of this type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.