I'm trying to resize a div based on the width of an image contained within it, but no JS method for grabbing the image's width seems to be working consistently.
<div class="main_image">
<img class="wp-post-image" src="">
<label>label here</label>
</div>
img {
width: auto;
height: auto;
max-width: 500px;
max-height: 450px;
}
var newWidth = document.getElementsByClassName("wp-post-image"[0].offsetWidth;
$(".wp-post-image").parent(".main_image").css({"width": newWidth});
I've tried with .style.width
, .width
, .offsetWidth
, .width()
, .outerWidth()
, .getBoundingClientRect.width()
For each of these, it correctly grabs the image width some of the time, but other times it has the image's width as 0. (Or 2 because it has a 1px border and that's the only part getting picked up, same deal.) The issue is definitely the grabbing of the width, not the setting, as tested with alerts.
The reason I need to resize this div is so that the image caption will wrap if it's wider than the image itself.
Is there something obvious I'm missing, either a reason this is happening or a better way to solve my problem?
Thanks!