How can I get the nearest next element that sattisfies some condition/function? Like:
nextEl = someEl.next(function() {... return true to return this from next() });
I’m not aware that the .next() method in jQuery API supports a function as an argument. Is there some trick to write it like this without doing a while loop?
Also I don’t want to select all elements first and then use filter() — this suboptimal from performance point of view.
Get all the next elements using
.nextAll(), then use.filter()and return the result of the condition. When the condition returnstrue, the element is kept.Then narrow it down to the
.first()match.Or if there will be many elements tested, and you don’t want to run the condition all those extra times, use
.each(), thenreturn false;when the condition is met. This halts the loop.EDIT: If you don’t want to select all the next elements, I’d go native, and use a
whileloop, something like this:The loop will break as soon as the condition is met, and the most recent assignment to
nextElwill be your element.If the condition is never met, the loop will end when it runs out of elements, and
nextElwill benullorundefined( I don’t remember which ).This should be a very quick way to do it.
EDIT:
Here’s a function version of it. It accepts the starting element and a function that runs the test. Then it returns the match found, or
undefined.LAST EDIT:
I guess I might as well make it into a plugin:
So now it’s more of a jQuery type solution. You still should have better performance since it doesn’t fetch all the next siblings, and the
whileloop still breaks once a match is found.