Cycling through sibling elements on button click and assigning a class to the “active” element I am attempting to do something that seems pretty simple, but I'm not sure if it as performant as it could be. I'm looking to cycle through a set of elements and toggle a class to only show a single item at a time, looping back to the first item at the end.

$(document).ready(() =&gt; {
  const toggleButton = $('.btn-toggle');
  toggleButton.on('click', function toggleButtonClick() {
    const currentItem = $(this).parent('.itemtoggle')
      .find('li:not(.d-none)').toggleClass('d-none');
    let nextItem = currentItem.next();
    if (nextItem.length === 0) {
      nextItem = currentItem.parent('.items').find('li');
    }
    nextItem.first().toggleClass('d-none');
  })
  .parent('.itemtoggle')
  .find('li')
  .toggleClass('d-none')
  .first()
  .toggleClass('d-none');
});


Full code example on Codepen

Right now it is written using jQuery. Is there a better way to do this, in jQuery, Vanilla JS, or other?
You are doing a lot of DOM traversal. I'll show you the updated code and explain it.

HTML

&lt;div class="itemtoggle"&gt;
  &lt;ul class="items"&gt;
    &lt;li&gt;Item 1&lt;/li&gt;
    &lt;li class="d-none"&gt;Item 2&lt;/li&gt;
    &lt;li class="d-none"&gt;Item 3&lt;/li&gt;
    &lt;li class="d-none"&gt;Item 4&lt;/li&gt;
  &lt;/ul&gt;
  &lt;button type="button" class="btn-toggle"&gt;Toggle Next&lt;/button&gt;
&lt;/div&gt;


CSS

.d-none {
  display: none;
}


JAVASCRIPT

$(document).ready(() =&gt; {
  const toggleButton = $('.btn-toggle');
  const items = document.querySelectorAll('.items &gt; li');
  let index = 0;
  toggleButton.on('click', () =&gt; {
     $(items[index]).toggleClass('d-none');
     index = index + 1;
     if(index === items.length){
       index = 0;
     }
     $(items[index]).toggleClass('d-none');
  });
});


I updated the HTML so that the li's after the first have display none. In your previous code this was the initial state, so its better to set it in the HTML than using JavaScript to do it.

What i have done in JavaScript is that i store all &lt;li&gt; and an associated index, then when you press Toggle Next, i just toggle the &lt;li&gt; at the current index, and increment index by 1, if index === items.length, then it must mean we are out of bounds, because items[4] would be undefined, so we have to reset it to 0.

After increment, we toggle d-none on the new index.