Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the middle value of a class using JQuery

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>
like image 922
user3610762 Avatar asked May 08 '14 06:05

user3610762


4 Answers

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());
});
like image 72
Adil Avatar answered Nov 20 '22 18:11

Adil


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

like image 37
Felix Avatar answered Nov 20 '22 16:11

Felix


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

like image 5
Zaheer Ahmed Avatar answered Nov 20 '22 17:11

Zaheer Ahmed


Reference them by index

var myDivs = $('.myDivs'),
    third = myDivs.eq(2),
    fourth = myDivs.eq(3);

To get the text value, just use text()

like image 2
Phil Avatar answered Nov 20 '22 17:11

Phil