diff --git a/CHANGELOG.md b/CHANGELOG.md index 5737079..2e9634c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,14 @@ All notable changes to the `dom_query` crate will be documented in this file. ## [Unreleased] +### Added + +- Implemented `NodeRef::is_match` and `NodeRef::is` methods, which allow checking if a node matches +a given matcher (`&Matcher`) or selector (`&str`) without creating a `Selection` object. + + ### Changed + - `Selection`'s internal code changes aimed at reducing calls to `RefCell::borrow` and `RefCell::borrow_mut`. ## [0.11.0] - 2024-12-10 diff --git a/src/node/node_ref.rs b/src/node/node_ref.rs index 3e340ac..d776f58 100644 --- a/src/node/node_ref.rs +++ b/src/node/node_ref.rs @@ -14,6 +14,7 @@ use crate::entities::copy_attrs; use crate::Document; use crate::Tree; use crate::TreeNodeOps; +use crate::Matcher; use super::child_nodes; use super::id_provider::NodeIdProver; @@ -641,4 +642,14 @@ impl NodeRef<'_> { child = next_node; } } + + /// Checks if the node matches the given matcher + pub fn is_match(&self, matcher: &Matcher) -> bool { + matcher.match_element(self) + } + + /// Checks if the node matches the given selector + pub fn is(&self, sel: &str) -> bool { + Matcher::new(sel).map_or(false, |matcher| self.is_match(&matcher)) + } } diff --git a/tests/node-traversal.rs b/tests/node-traversal.rs index 35d094d..498547a 100644 --- a/tests/node-traversal.rs +++ b/tests/node-traversal.rs @@ -220,3 +220,15 @@ fn test_node_prev_sibling() { let prev_element_sibling_sel = Selection::from(prev_element_sibling.clone()); assert!(prev_element_sibling_sel.is("#first-child")); } + + +#[cfg_attr(not(target_arch = "wasm32"), test)] +#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)] +fn test_node_is() { + let doc = Document::from(ANCESTORS_CONTENTS); + + let parent_sel = doc.select_single("#parent"); + let parent_node = parent_sel.nodes().first().unwrap(); + assert!(parent_node.is("div#parent")); + assert!(parent_node.is(":has(#first-child)")); +} \ No newline at end of file