I have two divs with the same class .productList
, and want to manipulate the second <img>
in both divs with jQuery.
I have the following;
$('div.productList').each(function(){
$('img:last-child').css('margin-left','10px');
});
Markup (partial)
<div class="productList">
<img src="images/parts/" width="120" height="120" alt="" title="" />
<img class="last" src="images/parts/" width="120" height="120" alt="" title="" />
I assumed using .each()
would cycle through each div and find the last img
, but this is not working for me.
Could someone please point me in the right direction with this?
Thanks.
Just use css to do that:
div.productList img:last-child {
margin-left: 10px;
}
I agree with Ethan that you should just use CSS to do that, however, using the last-child
selector (as he recommends) will only work if the img
tag is in fact the last html element in .productlist
(i.e. no other div
, span
, etc. follows the img
tag--see example). Since you only showed partial markup, that is entirely unclear to me. If it is simply a series of img
tags, then use Ethan's answer, otherwise...
A better CSS3 solution is to use last-of-type
, as it will only look for elements of the type that is being sought (img
in this case). So if other elements follow it, it does not matter.
.productList img:last-of-type {
margin-left: 10px;
}
For Older Browsers not supporting CSS3, if your two img
tags in fact sit one after another in your mark-up, and they are the only paired up img
tags in the .productList
, then a solution for those older browsers (which also would work in newer, CSS3 browsers) would be to use the adjacent sibling selector:
.productList img + img {
margin-left: 10px;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With