Cannot Select Direct Child from *goquery.Selection

1.6k views Asked by At

In jQuery and CSS, you can use the > character which points to only the direct child element.

This works in Goquery with something like doc.Find("body > ul"), but when you already have a *goquery.Selection and you want to select a direct child element of the selection, how can this be done?

For example:

doc.Find("body > ul > li") // Works

doc.Find("body > ul > li").Each(func(i int, s *goquery.Selection) {
    s.Find("> ul") // Does not work
})

I want to accomplish what you'd expect to be selected from the second block of code but I haven't had any success with this.

How can this be done?

1

There are 1 answers

5
AudioBubble On

As noted in this cascadia ticket (the selector library that goquery uses), this functionality is not (and will not be) implemented.

The simplest workaround would be to use the ChildrenFiltered() method on your selection:

doc.Find("body > ul > li").Each(func(i int, s *goquery.Selection) {
    s.ChildrenFiltered("ul")
})