grafana/k6 · error

the argument to each() must be a function

Error message

the argument to each() must be a function

What it means

In k6's HTML module (parseHTML), Selection.Each() mirrors jQuery's each() and only accepts a callback function invoked as (index, element). The Go implementation calls sobek.AssertFunction and throws immediately when the argument is not callable. Note that unlike jQuery, a selector string is not accepted here.

Source

Thrown at js/modules/k6/html/html.go:370

		return s.rt.ToValue(valueOrHTML(selected))

	default:
		return sobek.Undefined()
	}
}

func (s Selection) Children(def ...string) Selection {
	if len(def) == 0 {
		return Selection{s.rt, s.sel.Children(), s.URL}
	}

	return Selection{s.rt, s.sel.ChildrenFiltered(def[0]), s.URL}
}

func (s Selection) Each(v sobek.Value) Selection {
	sobekFn, isFn := sobek.AssertFunction(v)
	if !isFn {
		common.Throw(s.rt, errors.New("the argument to each() must be a function"))
	}

	fn := func(idx int, _ *goquery.Selection) {
		if _, err := sobekFn(v, s.rt.ToValue(idx), selToElement(Selection{s.rt, s.sel.Eq(idx), s.URL})); err != nil {
			common.Throw(s.rt, fmt.Errorf("the function passed to each() failed: %w", err))
		}
	}

	return Selection{s.rt, s.sel.Each(fn), s.URL}
}

func (s Selection) Filter(v sobek.Value) Selection {
	switch val := v.Export().(type) {
	case string:
		return Selection{s.rt, s.sel.Filter(val), s.URL}

	case Selection:
		return Selection{s.rt, s.sel.FilterSelection(val.sel), s.URL}

View on GitHub (pinned to 93accf6570)

Solutions

  1. Pass a function: sel.each((i, el) => { ... })
  2. Filter first with .find()/.filter() if the intent was to narrow the selection, then call each() with the callback
  3. If iterating without an index, still declare the callback signature (idx is always provided)

Example fix

// before
selection.each('div');

// after
selection.find('div').each((idx, el) => { console.log(el.nodeName()); });
Defensive patterns

Strategy: type-guard

Type guard

const isFn = (v) => typeof v === 'function';
if (!isFn(cb)) throw new TypeError('each() expects a function');
sel.each(cb);

Prevention

When it happens

Trigger: Calling sel.each() with anything other than a function: a selector string ('sel.each("div")'), no argument (undefined), or an object.

Common situations: Porting jQuery code where a string filter was tolerated; forgetting the callback during refactoring; passing a Selection instead of iterating its elements.

Related errors


AI-assisted analysis of grafana/k6@93accf6570 (2026-08-15). Data as JSON: /api/errors/249703953fadc2e2. Report an issue: GitHub.