Search code examples
k6

k6: How to create a Selection from an Element


Using Selection.each(fn) (see the k6 docs), the callback is passed an index and an Element. Element has a different API than Selection, and within the callback I’d like to use the Selection API on the passed Element so that I can operate on each Selection individually. In jQuery, I’d often do this:

$('li').each(function (index, element) {
  let container = $(element).closest('div.listContainer');
  // now do something with the `container`
});

I’ve tried inside the callback to do things like $(element) or Selection(element) but it errors saying those are undefined. (Kind of stabbing in the dark, since I don’t see in the docs how to do this.)

My code looks like:

mySelection.each((index, element) => {
  // here, I'd like to do element.closest('.someAncestorSelector') if element could be 'wrapped'
})

Is there a way in the jQuery-like Selection API in k6 to do this?


Solution

  • From the k6 docs on Selection.closest:

    For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. [emphasis mine]

    Which means that each is unnecessary and will be performed automatically (returning a new Selection instance with the closest elements).

    const closestSelection = mySelection.closest('.someAncestorSelector');
    closestSelection.each((index, closestElement) => {
      // now, do something with closestElement.
    });
    

    or as a single chain of expressions:

    mySelection.closest('.someAncestorSelector')
      .each((index, closestElement) => {
        // now, do something with closestElement.
      });
    

    Btw, even jQuery implicitly handles collections, so your jQuery code could be changed to:

    const containers = $('li').closest('div.listContainer');
    containers.each(function (index, container) {
      container = $(container);
      // now do something with the `container`
    });