jQuery to loop through elements with the same clas

2019-01-01 17:08发布

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?

14条回答
路过你的时光
2楼-- · 2019-01-01 17:14

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

查看更多
还给你的自由
3楼-- · 2019-01-01 17:15

Without jQuery updated

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

查看更多
看淡一切
4楼-- · 2019-01-01 17:15

In JavaScript ES6 using spread ... operator

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

over a array-like collection given by 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>

查看更多
琉璃瓶的回忆
5楼-- · 2019-01-01 17:16

you can do it this way

$('.testimonial').each(function(index, obj){
    //you can use this to access the current item
});
查看更多
人气声优
6楼-- · 2019-01-01 17:22
$('.testimonal').each(function(i,v){
  if (condition) {
    doSomething();
  }
});
查看更多
余生请多指教
7楼-- · 2019-01-01 17:25

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:

var testimonials = document.querySelectorAll('.testimonial');
Array.prototype.forEach.call(testimonials, function(elements, index) {
    // conditional here.. access elements
});
查看更多
登录 后发表回答