0

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

Kleajmp
  • 167
  • 1
  • 9
  • 1
    You know you can do this with CSS...right? – Paulie_D Aug 20 '16 at 15:37
  • Only the opposite way no? All images have a different width and the container needs to take over this custom width. If I'm wrong please tell me how? – Kleajmp Aug 20 '16 at 15:54
  • See this question and answer...http://stackoverflow.com/questions/37884416/is-it-possible-to-wrap-the-contents-of-this-div-based-on-one-element-over-anothe – Paulie_D Aug 20 '16 at 15:56

1 Answers1

0

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
guest271314
  • 1
  • 15
  • 104
  • 177
  • Man, that fixed it! I never knew you could use a second argument **this** into a **$** selector like: '$("img", this)'. I'm grateful. – Kleajmp Aug 20 '16 at 15:50
  • @Kleajmp _"I never knew you could use a second argument this into a $ selector like: '$("img", this)'."_ See [`jQuery( selector [, context ] )`](http://api.jquery.com/jquery/#jQuery-selector-context) – guest271314 Aug 20 '16 at 15:53
  • yes, designers who try to use scripting... don't understand what they meant with 'context'. But now I do! Thanks again for the clear explanation. I'll write this on my wall. – Kleajmp Aug 20 '16 at 16:43