Reputation: 515
<div class="divclass">
<ul>
<div class="lidiv"> <li><img src="img1.jpg"/></li> </div>
<div class="lidiv"> <li><img src="img2.jpg"/></li> </div>
<div class="lidiv"> <li><img src="img3.jpg"/></li> </div>
<div class="lidiv"> <li><img src="img4.jpg"/></li> </div>
<div class="lidiv"> <li><img src="img5.jpg"/></li> </div>
</ul>
</div>
How i get the image width? All images are in different width. I want to get the image width and i give it to the div class="lidiv". Any one can help? please!
Upvotes: 0
Views: 2735
Reputation: 15104
$('.divClass ul li img').width();
This code should works. But Rory McCrossan is right, your html is invalid. The browser may remove the div
tag inside the li
, so you can access it in javascript.
But you can give a width to the li
tag :
$('.divClass ul li').each(function() {
var $li = $(this);
$li.width($li.find('img').width());
});
Warning : On some browser, the DOMReady event is fired before the image loading ! So if you get a 0 width (or undefined
), you should execute this code later. You can listen to the images load event :
$('.divClass ul li img').load(function() {
var $img = $(this);
$img.parent().width($img.width());
});
Upvotes: 1
Reputation: 66
First loop over de div-items. Then select the descendant img-element. After getting the image width, put it in the css-style of the div.
$(document).ready(function(){
$("div.lidiv").each(function() {
img = $(this).find('img');
img_width = img.width();
$(this).css('width', img_width);
});
});
Upvotes: 1
Reputation: 802
Try this
var imgWidth = jQuery('img').clientWidth;
and write valid HTML.
Upvotes: 0