Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select first ten elements using nth-of-type in jQuery

I'm trying to target the first ten images on my page which have a class of .lazy

I'm using unveil to lazy load images, it waits for a scroll to load images but you can trigger all images to load with this line:

$("img").trigger("unveil");

I want to trigger just the first 10 images to always show straightaway, so I've tried this:

$("#portfolio .portfolio-item img.lazy:nth-of-type(-n+10)").trigger("unveil");

In CSS :nth-of-type(-n+10) selects the first ten matching elements, but when I try this out on my console using this jQuery

$("img.lazy:nth-of-type(-n+10)")

..it returns every img with the class of .lazy

What am I doing wrong? is there a way to select the first ten instead using jQuery's .eq?

to give you some idea of my markup:

<div class="portfolio">
     <div class="portfolio-item">
          <img class="lazy" src="item-1.jpg">
     </div>
     <div class="portfolio-item">
          <img class="lazy" src="item-2.jpg">
     </div>
     <div class="portfolio-item">
          <img class="lazy" src="item-3.jpg">
     </div>
     <div class="portfolio-item">
          <img class="lazy" src="item-4.jpg">
     </div>
     etc... (there 20 items in total)
</div>

is the issue that each img is nested within a separate parent?

like image 512
Pixelomo Avatar asked Dec 24 '22 17:12

Pixelomo


2 Answers

You can use lt selector to select first n elements.

Select all elements at an index less than index within the matched set.

$("#portfolio .portfolio-item img.lazy:lt(10)").trigger("unveil");

Demo

like image 176
Tushar Avatar answered Jan 18 '23 14:01

Tushar


You can also use slice(). Slice is more powerful in a sense that you can apply properties between a range of elements

$("#portfolio .portfolio-item img.lazy").slice(0,10).trigger("unveil");

Here is a code snippet:

$(document).ready(function() {
  $('div').slice(2, 5).css('background-color', 'red');
});
div {
  border: 1px solid black;
  height: 50px;
  width: 50px;
  display: inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
like image 22
Siddharth Thevaril Avatar answered Jan 18 '23 15:01

Siddharth Thevaril