I need to dynamically set the width of each image caption based on the width of its corresponding image in the img-wrap class. The current code is only applying the width from the first image to all captions.
<div class="img-wrap">
<img src="http://lorempixel.com/300/100" />
<div class="img-caption">aa</div>
</div>
<div class="img-wrap">
<img src="http://lorempixel.com/400/100" />
<div class="img-caption"></div>
</div>
<div class="img-wrap">
<img src="http://lorempixel.com/500/100" />
<div class="img-caption">cc</div>
</div>
<script>
var imgwidth = 0;
$('.img-wrap').each(function (index, value) {
imgwidth = $(this).find('img').width();
if ($(this).find('.img-caption').text() === '') {} else {
$(this).css("background-color", "#000");
$(this).css("color", "#fff");
$(this).css("width", imgwidth);
}
});
</script>
The goal is to have each img-caption's width match that of its corresponding image. Currently, they are all inheriting the width of the first image. Any insights on how to achieve this specific width assignment would be greatly appreciated!