Javascript: Can I query for only the next n elements after a certain class?

New to JS. Is there a simple way to query for only the next n number of elements after a certain element/class? Sibling elements, not children. For example, let’s say I have this html:

<span>Empty</span>
<span>Empty</span>
<div class="start">Empty Block</div>
<span>Content 1</span>
<span>Content 2</span>
<span>Content 3</span>
<span>Content 4</span>
<span>Content 5</span>

I want to perform a document.querySelect, but I only want to bring back the first 3 spans that come after the <div class="start"> (so, only Content 1, Content 2 and Content 3). Something like this in the JS:

startingDiv = document.getElementsByClassName('.start');
allSpansAfterDiv = $(".start").nextAll('span');
targetSpans = allSpansAfterDiv[0,3];

The last line was what I was hoping would return the first 3 spans under the div, but in the console log it’s only returning the last item I have in the brackets, so [3], which is equivalent to <span>Content 4</span> in the HTML.

I tried to see if I could make these two jQuery options work as well:

Option 1:

$('span:lt(4)');

Option 2:

$('span').slice(0,4)

But these will target all the spans on the page. I wasn’t sure how to start counting the spans only after the <div class="start">.

How can I choose just the first 3 spans after the <div class="start">?

If it helps to know what I’m trying to use this for in real life:

I have a page with 20 blog posts on it, each post enclosed in an <article> tag. I want to show the 5 most recent posts at first, with a “Load More” button you can click to show the next 5 posts. I want to tell the Load More button to grab the next 5 <article> elements and change them from display: none to display: block. Right now, all I’m trying to figure out is how to target the next 5 articles after the button. The position of the button on the page will be constantly changing each time it’s clicked.

Answer

You are well on the right track. You can slice() the collection returned by nextAll()

Or use the :lt(3) selector in the nextAll()

For a “Show More” you could use a :gt() to hide the ones greater than your threshold, then filter :hidden with a slice() or :lt() when you want to show them

$('.start').nextAll('span').slice(0,3).css('color','red')
$('.start').nextAll('span:lt(3)').css('background-color','yellow')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span>Empty</span>
<span>Empty</span>
<div class="start">Empty Block</div>
<span>Content 1</span>
<span>Content 2</span>
<span>Content 3</span>
<span>Content 4</span>
<span>Content 5</span>