Reputation: 6458
i have a list of images, with the same class name in my dom as follows:
<a href="#"><img class="vote" src="http://2.bp.blogspot.com/_XeuZ1yDnv4Q/TSUkAT6T1dI/AAAAAAAADR8/nPHP4JvVxy8/s1600/vote.jpg"></a>
<a href="#"><img class="vote" src="http://bgathinktank.files.wordpress.com/2011/01/vote-button.jpg"></a>
now say given a list of widths in a js array
width = [100, 200]
i want the first image to have a width of 100 and second one a width of 200.
How can that be done using jquery?
Upvotes: 0
Views: 60
Reputation: 1133
$('img.vote').each(function(i) {
$(this).attr('width', width[i]);
});
Upvotes: 0
Reputation: 30666
$('.vote')
finds all elements with class '.vote'.
.each() iterates through all images. The callback can receive two parameters: the current index and the current DOM element. We don't need the latter as this
is also the current DOMelement in the callback.
.width() sets the width of each element in the matched set, here the current image $(this)
Here's the code:
var width = [100, 200];
var $imgs = $('.vote');
$imgs.each(function(idx) {
$(this).width(width[idx]);
});
Upvotes: 2