Nick
Nick

Reputation: 2551

jQuery - Loop through variable/elements?

I'm trying to load specific products into divs but each div is only loading in the first product. I'm guessing I need to do a loop of some sort but I'm not quite sure how

Here's what I'm trying to do:

<div class="prdContainer" rel="prod-1"></div>
<div class="prdContainer" rel="prod-2"></div>
<div class="prdContainer" rel="prod-3"></div>

$(document).ready(function() {
    var prdNo = $('.prdContainer').attr('rel').split('-')[1];

    $('.prdContainer').load('http://www.domain.com .product:nth-child(' + prdNo + ')');
});

In my mind this is what it SHOULD be doing:

$('.prdContainer').load('http://www.domain.com .product:nth-child(1)');
$('.prdContainer').load('http://www.domain.com .product:nth-child(2)');
$('.prdContainer').load('http://www.domain.com .product:nth-child(3)');

Which would be associated with:

rel="prod-1"
rel="prod-2"
rel="prod-3"

Any help would be great!

Upvotes: 0

Views: 40

Answers (2)

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

$(document).ready(function() {  
  $('.prdContainer').each(function(i){
    $(this).load('http://www.domain.com .product:nth-child(' + (i + 1)+ ')');
  });
});

you should know that index starts from 0

Upvotes: 3

meskobalazs
meskobalazs

Reputation: 16041

Use the attribute equals selector (official docs):

$('.prdContainer[rel="prod-' + prdNo + '"]').load(...);

Upvotes: 0

Related Questions