nsilva nsilva - 4 months ago 7
Javascript Question

Hiding incremental values between a range

So taking the following HTML:-

<div id="news-archive">
<div id="blog-1" class="blog-wrapper">some content</div>
<div id="blog-2" class="blog-wrapper">some content</div>
<div id="blog-3" class="blog-wrapper">some content</div>
<div id="blog-4" class="blog-wrapper">some content</div>
<!-- and so on -->
</div>


And lets say the blog increment continues to 150.

Is it possible with CSS to only show the first 6 divs, i.e.
#blog-1
through to
#blog-6
and then hide the rest or is this a jQuery job?

Answer

You can achieve this in CSS using the nth-child selector:

#news-archive div {
    display: none;
}
#news-archive div:nth-child(-n+6) {
    display: block;
}

#news-archive div {
    display: none;
}
#news-archive div:nth-child(-n+6) {
    display: block;
}
<div id="news-archive">
    <div id="blog-1" class="blog-wrapper">some content 1</div>
    <div id="blog-2" class="blog-wrapper">some content 2</div>
    <div id="blog-3" class="blog-wrapper">some content 3</div>
    <div id="blog-4" class="blog-wrapper">some content 4</div>
    <div id="blog-5" class="blog-wrapper">some content 5</div>
    <div id="blog-6" class="blog-wrapper">some content 6</div>
    <div id="blog-7" class="blog-wrapper">some content 7</div>
    <div id="blog-8" class="blog-wrapper">some content 8</div>
    <div id="blog-9" class="blog-wrapper">some content 9</div>
    <div id="blog-10" class="blog-wrapper">some content 10</div>
    <div id="blog-11" class="blog-wrapper">some content 11</div>
    <div id="blog-12" class="blog-wrapper">some content 12</div>
</div>

However it may be worth you using AJAX to load only the required elements instead, as loading 140+ items on the page which will never be used will affect performance for no benefit.