780

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?

0

15 Answers 15

1379

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.

Sign up to request clarification or add additional context in comments.

9 Comments

The function with i, obj parameters helps a lot. If just each was used then it was not iterating.
@Darwindeeds correct! The function is used by the actual iterator to process each item. Returning false will stop iteration.
It is worth pointing out, that "obj" will be the dom object, while $(this) is the jQuery object.
Cant we do jQuery(this 'ul li').length to get length of that elements ul li?
+1 for suggesting $(this) to access the object... obj being DOM object doesn't allow to attach functions directly for example obj.empty()
|
171

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){

    }


 });

1 Comment

FYI: break; will not break. You must use return false;
73

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
});

Comments

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

Comments

33

you can do it this way

$('.testimonial').each(function(index, obj){
    //you can use this to access the current item
});

Comments

29

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/

Comments

28

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
}

2 Comments

this is the most efficient approach indeed.
I like this because the element is a jQuery object.
20
divs  = $('.testimonial')
for(ind in divs){
  div = divs[ind];
  //do whatever you want
}

2 Comments

that doesn't give you the jquery objects though, just dom elements
@celwell can't expect jQuery to do everything for you. It is a matter of making your own jQuery Object $(ind).
19

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');
}

Comments

18

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();

Comments

11

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
    }
});

Comments

10

Without jQuery updated

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

1 Comment

almost the same answer is already here, I think you should edit existing
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>

2 Comments

The spread operator + array notation is not needed, surely doing doc..torAll.forEach() would suffice?
Thank you. Absolutely. [...ArrayLike] was used for the time querySelectorAll didn't had support for .forEach. @aabbccsmith
7
$('.testimonal').each(function(i,v){
  if (condition) {
    doSomething();
  }
});

Comments

4

More precise:

$.each($('.testimonal'), function(index, value) { 
    console.log(index + ':' + value); 
});

1 Comment

This is nice if you like reading/writing from a more functional perspective.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.