Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implemented NodeRef::is_match and NodeRef::is #53

Merged
merged 1 commit into from
Dec 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)"));
}
Loading