whatf
whatf

Reputation: 6458

apply css to a list of classes in jquery

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

Answers (3)

Kevin
Kevin

Reputation: 1133

$('img.vote').each(function(i) {
    $(this).attr('width', width[i]);
});

Upvotes: 0

Didier Ghys
Didier Ghys

Reputation: 30666

  1. $('.vote') finds all elements with class '.vote'.

  2. .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.

  3. .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]);
});

DEMO

Upvotes: 2

SoWhat
SoWhat

Reputation: 5622

$('.vote').each(function(index){$(this).width(width[index])});

Upvotes: 1

Related Questions