Kleajmp Kleajmp - 3 months ago 10
CSS Question

jQuery: give each <figure> parent the same width as its <img> child

Each image container (figure) needs to take the width of the image (img) it contains and place a (figcaption) with the same width as the container.

If I use only one container it works but when I use multiple figures it sets every figure with the size of the first image.

So I'm making a logical mistake in the foreach loop, but can't find a solution. Any help? I'm pretty new in jQuery.

<figure><img><figcaption></figcaption></figure>
<figure><img><figcaption></figcaption></figure>
<figure><img><figcaption></figcaption></figure>

<script>
$(document).ready(function(){
//make figure the width of its image child
$('figure').each(function() {
var childWidth = $('figure img').width();
console.log(childWidth);
$('figure').width(childWidth);
})
});
<script>


look at the html/css code

Answer

You are selecting and setting all figure elements width within .each(). Substitute

var childWidth = $("img", this).width(); // selects current `figure` `img`

for

var childWidth = $('figure img').width(); // selects all `img` elements

and

$(this).width(childWidth); // selects current `figure`

for

$('figure').width(childWidth); // selects all `figure` elements