tags:

views:

45

answers:

3

for example i have the markup

<div>
     <img src="#" alt=""/>
     <img src="#" alt=""/>
     <img src="#" alt=""/>
<div>

I want to select $('div img') and then assign each one a z-index value so the first one is 3, second 2, third 1. Is this simple with jQuery?

Thanks

A: 

yep, use each function - http://api.jquery.com/each/

John
A: 

This should work, see the demo here by clicking on the preview button.

var total = $('div img').size();

$('div img').each(function(index){
  $(this).css('z-index', total - index);
});
Sarfraz
why down vote...........Co...you need a reply again?
Sarfraz
`$('div img')` is not cached = inefficient slow JavaScript. And it wasn't me who downvoted you so quit moaning.
Coronatus
@Coronatus: This question was not about **speeding up and optimizing the code of the questioner**, and that is kinda tedious and lastly i did not vote you down either. You could have shown the caching stuff in your own answer if you think questioner was worried about speed.
Sarfraz
A: 
i = 3;

$('div img').each(function()
{
    $(this).css('z-index', i);

    i -= 1;
});
Coronatus
`$('div img')` is not cached = inefficient slow JavaScript. You should edit the solution for that.
Sarfraz
It is only called once so there is no need for caching. Get a clue.
Coronatus
@Coronatus: Then you should not suggest the same to others. Try to be a responsible, helper fellow, you are here to help others not just to get reputation points. I hope you read my article on SO tips on tricks on my blog. Thanks
Sarfraz
Sarfraz, please learn what you are talking about before talking. Your answer DOES need caching because the selector is done TWICE, mine does not.
Coronatus