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

Anchor selector to current element ref #58

Closed
demurgos opened this issue Feb 13, 2021 · 1 comment
Closed

Anchor selector to current element ref #58

demurgos opened this issue Feb 13, 2021 · 1 comment

Comments

@demurgos
Copy link

Suppose I have the following HTML:

<body>
<article id="a">
  <div>First</div>
  <div>Before<div>Nested</div>After</div>
  <div>Last</div>
</article>
<article id="b">
  <div>Some other article</div>
</article>
</body>

My goal is to scrape the first article and get its id and number of direct-child <div>s. Ignoring error handling, I could use something like:

pub fn scrape(doc: ElementRef) -> (String, usize) {
  let first_article = doc.select(&Selector::parse("article").unwrap()).next().unwrap();
  let id = first_article.value().attr("id").unwrap().to_string();

  let content_count = doc.select(&Selector::parse("article:first-of-type > div").unwrap()).count();

  (id, content_count) // ("a", 3)
}

There are a few issues with this code. The first one is that article:first-of-type is not the same as getting the first article match. In this case it's ok, but in general it's more brittle. The next one is that I am traversing more nodes that needed: I already have a reference to the first article and should be able to start the traversal from there with first_article.select.

The problem is that the > direct-child operator needs a left-side. How can I reference the current scope? More precisly, what should be the value of ??? in the following code?

  let content_count = first_article.select(&Selector::parse("??? > div").unwrap()).count();

I tried to use the following values:

  • :root: Document root
  • :host: Shadow-element root
  • &: Sass sigil referring to the current scope

Is it possible to reference the current scope in the selector or is this behavior unsupported at all?

@demurgos
Copy link
Author

demurgos commented Feb 13, 2021

I actually found that I should use :scope, MDN has a section describing exactly my use case. Using it fixed my problem. I hope this issue may help other having the same issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant