Reputation: 291
I'm trying to have jQuery find the height/width attributes for the image inside the div with the class "image" and then apply those values as css to the div with the class "overlay" which is a child of "image". The code below is what i've got so far. It works great for one instance of "image". But I'm not sure how to make it go through every instance of "image" and apply the correct values to "overlay". I played around with .each but I couldn't get it to work.
HTML:
<div class="image">
<img src="some-img" width="400" height="200" />
<div class="overlay"></div>
</div>
jQuery:
var height = $("img").attr("height");
var width = $("img").attr("width");
$(".overlay").css({
height: height,
width: width
});
Thanks in advance!
Upvotes: 1
Views: 95
Reputation: 253318
I'd suggest:
$('.image img').each(
function(){
var that = $(this),
h = that.height(),
w = that.width();
that.next().css({ 'height' : h, 'width' : w });
});
Upvotes: 2
Reputation: 664425
$(".image").each(function(index, el) {
var $img = $("img", this); // equivalent: $(this).find("img")
$(".overlay", this).css({
height: $img.attr("height"),
width: $img.attr("width")
});
});
You also could iterate over the img
elements themselves and use .next()
to get the respective overlay.
Upvotes: 3