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

I am trying to target the first ten images on my page that have the class .lazy

I am using unveil for lazy loaded images, it expects scrolling to load images, but you can trigger all images to load with this line:

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

I only want to call the first 10 images that always show at once, so I tried this:

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

      

In CSS the :nth-of-type(-n+10)

first ten matched elements are selected, but when I try to accomplish this in my console using this jQuery

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

      

.. it returns every img with a class .lazy

What am I doing wrong? is there a way to select the top ten instead of using jQuery .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>

      

- the problem is that each img is nested in a separate parent?

+3


source to share


2 answers


You can use lt

to select the first items n

.

Select all items at index

less than the index in the matched set.



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

      

Demo

+6


source


You can also use slice()

. Slice is more powerful in the sense that you can apply properties between a range of items

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

      



Here is a violin

+3


source







All Articles