How can I get the third and forth value of class="myDivs"
using jQuery?
Below is my code:
HTML :
<div class="myDivs">Stack</div>
<div class="myDivs">Over</div>
<div class="myDivs">Flow</div>
<div class="myDivs">And</div>
<div class="myDivs">Exchange</div>
<div class="myDivs">Question</div>
<div class="myDivs">Ask</div>
You can use :eq to get the element at particular indexes.
Live Demo
$('.myDivs:eq(2), .myDivs:eq(3)').each(function(){
alert($(this).text());
});
Using the combination of :gt and :lt will give you range. It is useful when you have many elements.
Live Demo
$('.myDivs:gt(1):lt(2)').each(function(){
alert($(this).text());
});
Edit To make it dynamic so that you do not have to hard code the middle you can divide the length of element collection and use it for start point, this will make it work independant of how many elements you have with class myDivs
.
Live Demo
mid = Math.floor($('.myDivs').length /2) -2;
$('.myDivs:gt(' + mid +'):lt(2)').each(function(){
alert($(this).text());
});
You can use .slice()
Reduce the set of matched elements to a subset specified by a range of indices
and push the text value into an array using .map():
var valArr = $('.myDivs').slice(2,4).map(function() {
return this.textContent;
}).get();
Fiddle Demo
One dynamic way is to calculate by the length of class count.
var mid1=Math.ceil($('.myDivs').length/2) - 1,
mid2=Math.floor($('.myDivs').length/2) - 1;
if(mid1===mid2){
//handle the case
}
$('.myDivs:eq('+mid1+'), .myDivs:eq('+mid2+')').each(function(){
alert($(this).text());
});
Here is demo
Reference them by index
var myDivs = $('.myDivs'),
third = myDivs.eq(2),
fourth = myDivs.eq(3);
To get the text value, just use text()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With