4

Could you help me break out a loop of goquery Each looping? I used "return" but it doesn't get out of loop, just pass the iteraction... How can I break out an Each looping in the following code:

doc.Find("td").Each(func(i int, s *goquery.Selection) {
    summary := s.Text()
    if summary == "--" {
        //I want to break the Each loop here
    }
}
Paulo Farah
  • 323
  • 2
  • 11

2 Answers2

2

Use the EachWithBreak method

doc.Find("td").EachWithBreak(func(i int, s *goquery.Selection) bool {
    summary := s.Text()
    if summary == "--" {
        return false
    }
    return true
})
jmaloney
  • 11,580
  • 2
  • 36
  • 29
0

In goquery 1.7.1 iteration.go, it says:

It is identical to Each except that it is possible to break out of the loop by returning false in the callback function.

So you need to return false to break the loop.

Marco Sacchi
  • 712
  • 6
  • 21
Nan Ni
  • 1
  • Always add a link to the documentation you refer to as well as paste the relevant part into the response (as you did), and add a snippet of code if applicable, so that you can give more complete information next time. It also points out that `EachWithBreak` should be used instead of `Each`. – Marco Sacchi Sep 29 '21 at 16:14