{"record":{"id":"41de64c7dd65d7b2","repo":"grafana/k6","slug":"the-function-passed-to-each-failed-w","errorCode":null,"errorMessage":"the function passed to each() failed: %w","messagePattern":"the function passed to each\\(\\) failed: %w","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"js/modules/k6/html/html.go","lineNumber":375,"sourceCode":"}\n\nfunc (s Selection) Children(def ...string) Selection {\n\tif len(def) == 0 {\n\t\treturn Selection{s.rt, s.sel.Children(), s.URL}\n\t}\n\n\treturn Selection{s.rt, s.sel.ChildrenFiltered(def[0]), s.URL}\n}\n\nfunc (s Selection) Each(v sobek.Value) Selection {\n\tsobekFn, isFn := sobek.AssertFunction(v)\n\tif !isFn {\n\t\tcommon.Throw(s.rt, errors.New(\"the argument to each() must be a function\"))\n\t}\n\n\tfn := func(idx int, _ *goquery.Selection) {\n\t\tif _, err := sobekFn(v, s.rt.ToValue(idx), selToElement(Selection{s.rt, s.sel.Eq(idx), s.URL})); err != nil {\n\t\t\tcommon.Throw(s.rt, fmt.Errorf(\"the function passed to each() failed: %w\", err))\n\t\t}\n\t}\n\n\treturn Selection{s.rt, s.sel.Each(fn), s.URL}\n}\n\nfunc (s Selection) Filter(v sobek.Value) Selection {\n\tswitch val := v.Export().(type) {\n\tcase string:\n\t\treturn Selection{s.rt, s.sel.Filter(val), s.URL}\n\n\tcase Selection:\n\t\treturn Selection{s.rt, s.sel.FilterSelection(val.sel), s.URL}\n\t}\n\n\tsobekFn, isFn := sobek.AssertFunction(v)\n\tif !isFn {\n\t\tcommon.Throw(s.rt, errors.New(\"the argument to filter() must be a function, a selector or a selection\"))","sourceCodeStart":357,"sourceCodeEnd":393,"githubUrl":"https://github.com/grafana/k6/blob/01ffac6f245854c1b8adc6a69857c76a15f90022/js/modules/k6/html/html.go#L357-L393","documentation":"Selection.Each wraps the JS callback: if the sobek function invoked per matched element returns an error, it is re-thrown wrapped as \"the function passed to each() failed\". The root cause is an exception inside the user's each() callback in the test script, raised via common.Throw in the JS runtime.","triggerScenarios":"Thrown at js/modules/k6/html/html.go:375 when the library encounters an invalid state.","commonSituations":"See trigger scenarios.","solutions":["Fix the exception raised inside the each() callback (see the wrapped error/stack)","Wrap callback logic in try/catch inside the script if failures are expected"],"exampleFix":null,"handlingStrategy":"try-catch","validationCode":null,"typeGuard":null,"tryCatchPattern":null,"preventionTips":[],"tags":[],"backgroundTag":null,"analyzedSha":"01ffac6f245854c1b8adc6a69857c76a15f90022","analyzedAt":"2026-08-18T03:05:52.393Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-14T05:17:10.506Z"}