1

I'm trying to use lodash's _.partition on a jQuery collection of elements, like so:

const $elements = $('<div class="outer"><div class="thisOne">thisOne</div><div>not thisOne</div><div>nor thisOne</div></div>').children();
// the above line ends up printing {0: <div class="thisOne">thisOne</div>, 1: <div>not thisOne</div>, 2:<div>nor thisOne</div>, length: 3} I may have mis-rememebered how it gets there.
// regardless it's a list of $jQuery elements
const [$matched, $unmatched] = _.partition($elements, element => element.text() === "thisOne");

$matched.forEach(element => expect(element).toHaveClass("thisOne"));
$unmatched.forEach(element => expect(element).not.toHaveClass("thisOne"));

But my error is on the second line, where it says that element.text() is not a function.

I've seen this question jQuery .each() function with ES6 arrow functions and I don't think it counts as this isn't a jQuery array function like each, and should just opperate on each element. Changing it to (index, element) => element.text() === "thisOne" still doesn't work, so I can't think that's the reason at all.

What am I doing wrong?

AncientSwordRage
  • 7,086
  • 19
  • 90
  • 173

1 Answers1

2

The issue is that the result of _.partition($elements, element => element.text() === "thisOne") is that element is not a jQuery element, but a native dom element.

To correct this, you need to apply $(...) around element like so:

element => $(element).text()

That makes sure that each element is jQuery aware, before running jQuery function on it.

AncientSwordRage
  • 7,086
  • 19
  • 90
  • 173