Skip to content

Commit

Permalink
Merge pull request #53 from niklak/feature/node-is
Browse files Browse the repository at this point in the history
implemented `NodeRef::is_match` and `NodeRef::is`
  • Loading branch information
niklak authored Dec 28, 2024
2 parents 7cdd006 + 34f101c commit 180d641
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 0 deletions.
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions src/node/node_ref.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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))
}
}
12 changes: 12 additions & 0 deletions tests/node-traversal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)"));
}

0 comments on commit 180d641

Please sign in to comment.