0

I'm using the jQuery .next() method to iterate list items. I need to use the .next() method to cycle through elements. .filter-selected is a dynamically added class on click that changes the style but also serves as a marker for the next element to be triggered.

Take this example:

<ul>
<li class="filter-selected title-available"><a href="#" class="filter-item">v</a></li>
    <li class="title-available"><a href="#" class="filter-item">item</a></li>
    <li class="title-unavailable"><a href="#" class="filter-item">item</a></li>
    <li class="title-available"><a href="#" class="filter-item">item</a></li>
    <li class="title-unavailable"><a href="#" class="filter-item">item</a></li>
</ul>

I have a button that the triggers this line:

$(".filter-selected").next("li.title-available").children().trigger('click');

The expected behavior is that it triggers only the li items that have the class .title-available but what happenes is when the class .filter-selected is above an li with .title-unavailable it triggers it anyways on .title-unavailable, even though I pass the specific classname into the .next() event that I want it to go next to li items with that classname only.

Why is that? Howcome passing a class into .next() doesn't control specific elements with specific classnames? Based on what I can see in the documentation you can do this. Howcome it doesn't work in my instance?

kawnah
  • 3,204
  • 8
  • 53
  • 103

1 Answers1

1

jQuery's next() retrieves only "the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector."

When the immediately following sibling does not match the selector, nothing is retrieved.

You might have more success using nextAll() and first() to select all matching subsequent siblings and then choose the first one.

$(".filter-selected").nextAll(".title-available").first().children().toggleClass('selected');
.selected {
  background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="filter-selected title-available"><a href="#" class="filter-item">v</a></li>
  <li class="title-unavailable"><a href="#" class="filter-item">item</a></li>
  <li class="title-unavailable"><a href="#" class="filter-item">item</a></li>
  <li class="title-available"><a href="#" class="filter-item">item</a></li>
  <li class="title-unavailable"><a href="#" class="filter-item">item</a></li>
</ul>
showdev
  • 28,454
  • 37
  • 55
  • 73