Set one element width equal to another

Hi,

I’d like to set the div width equal to the image width. Here’s what I can think of:

<script type="text/javascript">
window.onload = function ()
{
document.getElementById('foo').style.width = document.getElementById('bar').width + 'px';
}
</script>
<div id="foo" style="background:red;"><img id="bar" src="image.jpg"></div>

It seems to be working, but I’m not sure if it’s correct coding.

Thanks in advance for checking the code or any improvement you suggest!
Rain lover

It works, but normally a div will automatically expand to fix the width of the content that’s inside it, so you shouldn’t need that script there at all, should you?

Thanks for the answer, but the div width is always larger than image width as it’s a block element. I want them to be equal.

I just want to point out that using scripting for this is a heavy-handed technique compared with using CSS to achieve the the same result.

I’m glad it works out for you though.