简体   繁体   中英

Matching division widths with jquery

This is a question regarding matching division widths with jquery. Here is the html code I am working with.

<ul class="thumbs_container">
<li class="thumbs">
    <a class="fancybox" href="" >
        <div class="thumbs_image_container">
            <img src="" />
        </div>
        <div class="caption">
            caption
        </div>
    </a>
</li>
    <li class="thumbs">
    <a class="fancybox" href="" >
        <div class="thumbs_image_container">
            <img src="" />
        </div>
        <div class="caption">
            caption
        </div>
    </a>
</li>
</ul>

I will have multiple list items with the class 'thumbs'. What I want to do is match the widths of the divs with the class 'caption' to the widths of the divs with the class 'thumbs_image_container', but treating each list item separately.

Could someone please give me some pointers on how to do this? I know how to match the widths, but I am having problems figuring out how to treat each list item separately.

Use jQuery's each ( Jquery $.each selector )

This code will get the set of elements with class thumbs, then check if each element contains a class named caption, and if that element does contain caption, then it takes the related width on the element with class = thumbs_image_container and applies it to the iterated element.

$('.thumbs').each(function( location, element ){
 if( $(this).find('.caption').length){  
  var w = $(this).find('.thumbs_image_container')[0].width();
  $(this).width(w);
 }
});

Try using $.each()

var $ulWidth = $('thumbs_container').width();

$('li.thumbs').each( function() {

      var $divWidth = $(this).find('div.caption').width(); //Width of div inside Current li..

      if( parseInt($ulWidth) == parseInt($divWidth) ) {
           // Do Something
      }
});

Thanks Sushanth and Travis, jquery each did the trick, after experimenting this is what I ended up with which does what I was trying to do,

$('li.thumbs').each( function() {
var $divWidth = 0;  
$divWidth = $(this).find('img').width(); 
$(this).find('div.caption').width($divWidth);
});

it turns out it was the width of the image that I needed to match the 'caption' width to.

Thanks for the help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM