To ensure your script runs after all DOM elements have loaded, it's best practice to use the jQuery .ready()
event.
Check out this Fiddle for reference
Here is a snippet of the code:
$(document).ready(function() {
$('.item').each(function() {
var $this = $(this),
pic = $this.find('img');
if (pic.load) {
var w = pic.width();
var h = pic.height();
$this.width(w).height(h);
} else {
return;
}
});
alert("width : " + $('.item').width() + " & height : " + $('.item').height());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="item" style="width: 0px; height: 0px;">
<img src="http://dummyimage.com/190x100/000/fff.png
" alt="" />
</div>
Hopefully, this information proves helpful. Happy Coding :)
UPDATE::
There is another updated version available in this new fiddle
In this update, a dummy div
element has been added with dimensions matching the item
div.
Update #2:: It is important to wait until the image has loaded before running the script that determines its dimensions and applies them to the parent "item" div. To achieve this without waiting for the entire document DOM tree to be ready, you can utilize jQuery
.on("DOMready",".item img",function(){});
event function. This approach is similar to lazy-loading images.
Another update:: My answer has been further updated to consider scenarios where the image may not be fully loaded when the DOM is ready as discussed in the jQuery documentation for .ready() and .load() APIs.