jQuery pour faire une boucle à travers des éléments avec la même classe

j'ai une charge de divs avec la classe testimonial et je veux utiliser jquery pour faire une boucle à travers eux, à vérifier pour chaque div si une condition est vraie. Si c'est vrai, il doit effectuer une action.

est-ce que quelqu'un sait comment je ferais ça?

447
demandé sur Kees C. Bakker 2011-01-19 15:41:30

14 réponses

utilisez chaque: ' i ' est la position dans le tableau, obj est l'objet DOM que vous itérez (peut être accédé par le jquery wrapper $(this) ainsi).

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

cochez la case référence api pour plus d'information.

816
répondu Kees C. Bakker 2015-12-22 13:17:40

essayez ceci...

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


    if(condition){

    }


 });
104
répondu stephen776 2011-01-19 12:48:32

c'est assez simple de faire ça sans jQuery ces jours-ci.

sans jQuery:

il suffit de sélectionner les éléments et d'utiliser la .forEach() méthode pour itérer sur eux:

var testimonials = document.querySelectorAll('.testimonial');
Array.prototype.forEach.call(testimonials, function(elements, index) {
    // conditional here.. access elements
});
39
répondu Josh Crozier 2015-01-24 01:17:24

essayez cet exemple

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>

quand nous voulons accéder à ces divs qui ont data-index plus grand que 2 alors nous avons besoin de ce jquery.

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

violon d'exemple de travail

34
répondu Manoj 2017-02-19 11:46:26

, vous pouvez le faire de cette façon

$('.testimonial').each(function(index, obj){
    //you can use this to access the current item
});
26
répondu Ghyath Serhal 2011-01-19 12:49:55
divs  = $('.testimonial')
for(ind in divs){
  div = divs[ind];
  //do whatever you want
}
17
répondu ikostia 2011-01-19 12:45:00

vous pouvez le faire de manière concise en utilisant .filter . L'exemple suivant permet de masquer tous .divs testimonial contenant le mot "something":

$(".testimonial").filter(function() {
    return $(this).text().toLowerCase().indexOf("something") !== -1;
}).hide();
13
répondu karim79 2011-01-19 12:53:52

jQuery .eq () peut vous aider à parcourir les éléments avec une approche indexée.

var testimonialElements = $(".testimonial");
for(var i=0; i<testimonialElements.length; i++){
    var element = testimonialElements.eq(i);
    //do something with element
}
13
répondu Atharva 2013-12-09 06:02:24

il se peut que je manque une partie de la question, mais je crois que vous pouvez simplement faire ceci:

$('.testimonial').each(function() {
    if(...Condition...) {
        ...Do Stuff...
    }
}
8
répondu David Smith 2011-01-19 12:45:13

avec un simple pour boucle:

var testimonials= $('.testimonial');
for (var i = 0; i < testimonials.length; i++) {
  // Using $() to re-wrap the element.
  $(testimonials[i]).text('a');
}
7
répondu Ismail Rubad 2017-01-20 15:00:32

sans jQuery mise à jour

document.querySelectorAll('.testimonial').forEach(function (element, index) {
    element.innerHTML = 'Testimonial ' + (index + 1);
});
<div class="testimonial"></div>
<div class="testimonial"></div>
7
répondu KrisInception 2017-10-03 07:50:40
$('.testimonal').each(function(i,v){
  if (condition) {
    doSomething();
  }
});
6
répondu davin 2011-01-19 12:44:12

plus précis:

$.each($('.testimonal'), function(index, value) { 
    console.log(index + ':' + value); 
});
4
répondu Atif Tariq 2016-01-21 15:27:51

en JavaScript ES6 en utilisant spread ... operator

[...document.querySelectorAll('.testimonial')].forEach( el => {
    el.style.color = 'red';
});

plus d'un tableau "comme de la 151970920" collection Element.querySelectorAll()

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

<div class="testimonial" id="2">Lorem ipsum</div>
1
répondu Roko C. Buljan 2018-01-04 22:18:53