I want to get the first 3 elements in a div, so e1, e2 and e3:
<div id="parent">
<div id="e1">element 1</div>
<div id="e2">element 2</div>
<div id="e3">element 3</div>
<div id="e4">element 4</div>
</div>
I want to do this with jQuery. What’s the best way to achieve this?
Advertisement
Answer
Actually you can do this with nth-child pseudo-class with functional notation. So this will work like:
:nth-child(-n+3) Represents the first three elements. [=-0+3, -1+3, -2+3]
Where the functional notation represents elements in a list whose indices match those found in a custom pattern of numbers, defined by
An+B, where:Ais an integer step size,Bis an integer offset,nis all positive integers, starting from0.
So your final code would be something like:
const elements = document.querySelectorAll('#parent > div:nth-child(-n+3)')
elements.forEach(element => {
console.log(element.id)
})<div id="parent"> <div id="e1">element 1</div> <div id="e2">element 2</div> <div id="e3">element 3</div> <div id="e4">element 4</div> </div>
But if you want to stick with jQuery itself you can use jQuery :lt() instead. Where jQuery( ":lt(index)" ) Select all elements at an index less than index within the matched set
The output will be something like this:
const elements = $('#parent > div:lt(3)')
jQuery.each(elements, function (index, element) {
console.log(element.id)
})<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="parent"> <div id="e1">element 1</div> <div id="e2">element 2</div> <div id="e3">element 3</div> <div id="e4">element 4</div> </div>