[javascript] jQuery to loop through elements with the same class

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?

This question is related to javascript jquery jquery-selectors

The answer is


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

divs  = $('.testimonial')
for(ind in divs){
  div = divs[ind];
  //do whatever you want
}

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

_x000D_
_x000D_
document.querySelectorAll('.testimonial').forEach( el => {_x000D_
  el.style.color = 'red';_x000D_
  console.log( `Element ${el.tagName} with ID #${el.id} says: ${el.textContent}` );_x000D_
});
_x000D_
<p class="testimonial" id="1">This is some text</p>_x000D_
<div class="testimonial" id="2">Lorem ipsum</div>
_x000D_
_x000D_
_x000D_


you can do it this way

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

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

    }


 });

$('.testimonal').each(function(i,v){
  if (condition) {
    doSomething();
  }
});

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
}

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


More precise:

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

Without jQuery updated

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


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/


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

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

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to jquery-selectors

Why is my JQuery selector returning a n.fn.init[0], and what is it? How to use placeholder as default value in select2 framework Access the css ":after" selector with jQuery jQuery: using a variable as a selector Check if any ancestor has a class using jQuery jQuery selector first td of each row Select element by exact match of its content jQuery selector to get form by name jQuery : select all element with custom attribute Set select option 'selected', by value