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';
<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