kuchiki-rs / kuchiki

(朽木) HTML/XML tree manipulation library for Rust
MIT License
470 stars 54 forks source link

Question on `select` and its inclusive nature #81

Closed hipstermojo closed 4 years ago

hipstermojo commented 4 years ago

The select function in NodeRef is used to get all nodes matching a given CSS selector which is inclusive of the NodeRef that calls it. This works fine but could be cause for concern if the iterator it returns is then used to delete nodes. Is there a way to get a non inclusive iterator that does not involve using a if statement before looping?

Consider the following HTML

<div id="top">
  <div>foo</div>
  <div>bar</div>
  <p>baz</p>
</div>

In the following Rust code, we assume the node with the div#top selector is bound to a variable x:

let mut nodes = x.select("div").unwrap();
while let Some(node_ref) = nodes.next() {
  node_ref.detach();
}

This would delete div#top which is probably unintentional if a user only wanted to remove its <div> children.

SimonSapin commented 4 years ago

https://docs.rs/kuchiki/0.8.1/src/kuchiki/iter.rs.html#159-161 shows that NodeRef::select is implemented as:

        self.inclusive_descendants().select(selectors)

Try x.descendants().select("div") instead? https://docs.rs/kuchiki/0.8.1/kuchiki/iter/struct.Descendants.html#method.select

hipstermojo commented 4 years ago

Thanks! Using that works fine.