754

I have a load of divs with the class testimonial and I want to use jquery to loop through them to check for each div if a specific condition is true. If it is true, it should perform an action.

Does anyone know how I would do this?

Kees C. Bakker
  • 32,294
  • 27
  • 115
  • 203
geoffs3310
  • 13,640
  • 23
  • 64
  • 85

15 Answers15

1344

Use each: 'i' is the postion in the array, obj is the DOM object that you are iterating (can be accessed through the jQuery wrapper $(this) as well).

$('.testimonial').each(function(i, obj) {
    //test
});

Check the api reference for more information.

Kees C. Bakker
  • 32,294
  • 27
  • 115
  • 203
  • 3
    The function with i, obj parameters helps a lot. If just each was used then it was not iterating. – darwindeeds Jun 28 '12 at 16:22
  • 2
    @Darwindeeds correct! The function is used by the actual iterator to process each item. Returning `false` will stop iteration. – Kees C. Bakker Jun 29 '12 at 07:09
  • 190
    It is worth pointing out, that "obj" will be the dom object, while $(this) is the jQuery object. – AndreasT Sep 11 '12 at 10:50
  • Cant we do jQuery(this 'ul li').length to get length of that elements ul li? – techie_28 Sep 21 '12 at 06:09
  • $(this).find('ul li').length will give you the nummer of li's that are within all the ul's in the current scope. – Kees C. Bakker Sep 21 '12 at 09:37
  • I like this approach because the loop is in a separate scope (function), so there's no `i` variable after this loop. Variable names can be re-used/shadowed inside the loop without breaking anything on the outside. – basic6 Oct 12 '14 at 00:14
  • 22
    +1 for suggesting `$(this)` to access the object... `obj` being DOM object doesn't allow to attach functions directly for example `obj.empty()` – Fr0zenFyr Nov 17 '15 at 07:34
  • Worth noting that $.each('.testimonial', function(i, obj) { // do something } is NOT the same thing and will likely get a "Uncaught TypeError: Cannot use 'in' operator to search for" error. (yes, I got that and found this way that works! :) – Apps-n-Add-Ons May 23 '18 at 19:10
  • How to to this in JS? – streamc Nov 28 '19 at 02:11
165

try this...

$('.testimonial').each(function(){
    //if statement here 
    // use $(this) to reference the current div in the loop
    //you can try something like...


    if(condition){

    }


 });
stephen776
  • 9,134
  • 15
  • 74
  • 123
71

It's pretty simple to do this without jQuery these days.

Without jQuery:

Just select the elements and use the .forEach() method to iterate over them:

const elements = document.querySelectorAll('.testimonial');
Array.from(elements).forEach((element, index) => {
  // conditional logic here.. access element
});

In older browsers:

var testimonials = document.querySelectorAll('.testimonial');
Array.prototype.forEach.call(testimonials, function(element, index) {
  // conditional logic here.. access element
});
Community
  • 1
  • 1
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
54

Try this example

Html

<div class="testimonial" data-index="1">
    Testimonial 1
</div>
<div class="testimonial" data-index="2">
    Testimonial 2
</div>
<div class="testimonial" data-index="3">
    Testimonial 3
</div>
<div class="testimonial" data-index="4">
    Testimonial 4
</div>
<div class="testimonial" data-index="5">
    Testimonial 5
</div>

When we want to access those divs which has data-index greater than 2 then we need this jquery.

$('div[class="testimonial"]').each(function(index,item){
    if(parseInt($(item).data('index'))>2){
        $(item).html('Testimonial '+(index+1)+' by each loop');
    }
});

Working example fiddle

SaeX
  • 17,240
  • 16
  • 77
  • 97
Manoj
  • 4,951
  • 2
  • 30
  • 56
33

you can do it this way

$('.testimonial').each(function(index, obj){
    //you can use this to access the current item
});
Ghyath Serhal
  • 7,466
  • 6
  • 44
  • 60
27

jQuery's .eq() can help you traverse through elements with an indexed approach.

var testimonialElements = $(".testimonial");
for(var i=0; i<testimonialElements.length; i++){
    var element = testimonialElements.eq(i);
    //do something with element
}
Atharva
  • 6,711
  • 5
  • 31
  • 39
23

I may be missing part of the question, but I believe you can simply do this:

$('.testimonial').each((index, element) => {
    if (/* Condition */) {
        // Do Something
    }
});

This uses jQuery's each method: https://learn.jquery.com/using-jquery-core/iterating/

Yann Chabot
  • 4,789
  • 3
  • 39
  • 56
David Smith
  • 38,044
  • 11
  • 44
  • 61
20
divs  = $('.testimonial')
for(ind in divs){
  div = divs[ind];
  //do whatever you want
}
ikostia
  • 7,395
  • 6
  • 30
  • 39
18

With a simple for loop:

var testimonials= $('.testimonial');
for (var i = 0; i < testimonials.length; i++) {
  // Using $() to re-wrap the element.
  $(testimonials[i]).text('a');
}
Ismail Rubad
  • 1,458
  • 2
  • 13
  • 27
17

You can do this concisely using .filter. The following example will hide all .testimonial divs containing the word "something":

$(".testimonial").filter(function() {
    return $(this).text().toLowerCase().indexOf("something") !== -1;
}).hide();
karim79
  • 339,989
  • 67
  • 413
  • 406
10

Without jQuery updated

document.querySelectorAll('.testimonial').forEach(function (element, index) {
    element.innerHTML = 'Testimonial ' + (index + 1);
});
<div class="testimonial"></div>
<div class="testimonial"></div>
KrisInception
  • 155
  • 2
  • 6
10

You could use the jQuery $each method to loop through all the elements with class testimonial. i => is the index of the element in collection and val gives you the object of that particular element and you can use "val" to further access the properties of your element and check your condition.

$.each($('.testimonal'), function(i, val) { 
    if(your condition){
       //your action
    }
});
Nidhi Gupta
  • 101
  • 1
  • 4
8

In JavaScript ES6 .forEach() over an array-like NodeList collection given by Element.querySelectorAll()

document.querySelectorAll(".testimonial").forEach((el, idx) => {
  el.style.color = "red";
  console.log(`${idx} Element ${el.tagName} with ID #${el.id} says: ${el.textContent}` );
});
<p class="testimonial" id="1">This is some text</p>
<div class="testimonial" id="2">Lorem ipsum</div>
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
  • The spread operator + array notation is not needed, surely doing `doc..torAll.forEach()` would suffice? – alistair Jul 10 '19 at 19:25
  • Thank you. Absolutely. `[...ArrayLike]` was used for the time querySelectorAll didn't had support for `.forEach`. @aabbccsmith – Roko C. Buljan Jul 11 '19 at 11:32
7
$('.testimonal').each(function(i,v){
  if (condition) {
    doSomething();
  }
});
davin
  • 44,863
  • 9
  • 78
  • 78
4

More precise:

$.each($('.testimonal'), function(index, value) { 
    console.log(index + ':' + value); 
});
Atif Tariq
  • 2,650
  • 27
  • 34