theothersimon theothersimon - 6 months ago 12x
HTML Question

find child image width and apply it to containing parent div jquery

I have an

and some
's inside a

I want to get the width of the child img and apply it to the width of the parent div so that the paragraphs of text will wrap to the same width as the img.

I want to be able to do this to multiple iterations on the same page.

I am developing a wordPress theme that uses the masonry jquery plugin ( My theme has something in common with Gridalicious theme ( but the post widths and sizes will be dictated by the image width and will not be uniform.

My html/css is spotless but my jquery / javascript is pretty shaky - but if I can get some pointers I should be able to work with it.

Any help truly appreciated.


This works perfectly. Note that you have to use $(window).load() instead of $(document).ready(), because $(document).ready() fires before images are actually loaded, and thus the images will have no width.

$(window).load(function() {
    $('div').each(function() {

Edit: Note that this will base the width off of the first image in the div. Simply change the index ([0]) to base it off another image in the div.

Edit 2: Applied John's correction on the .width() function.