kuchiki-rs / kuchiki

(朽木) HTML/XML tree manipulation library for Rust

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Question on `select` and its inclusive nature

hipstermojo opened this issue · comments

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.

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

Thanks! Using that works fine.