Austin
Austin

Reputation: 25

Use JQuery each function to return element width

I currently have an ul with around 20 li. Each li is structured like this:

 <li class="block">
  <a href="#">
    <div class="front">
      <img src="..." />
    </div>
    <div class="back">
     <p>Text</p>
    </div>  
  </a>
</li>   

I would like to go through each li.block, find its width, and set the anchor tag's width equal to this number.

This is the function I'm using now, but it isn't working:

$(document).ready(function() {
  var $currentWidth = $("li.block").width();
  $( "li.block a" ).css( "width", $currentWidth);
});

What is the proper way to use .each() and something similar to the code above to fix my problem?

Upvotes: 1

Views: 72

Answers (2)

James Waddington
James Waddington

Reputation: 2905

To cycle through every block use

$("li.block").each(function() {//stuff});

Inside that function you can get the relevant block with this:

var width = $(this).width();

You can then apply that to the link inside that block:

$(this).children('a').css("width", $currentWidth);

Of course, that might be a little different if your html wasn't always like that - use whatever selector is appropriate.

So putting it all together, you would have something like this:

$("li.block").each(funtion() {
  var width = $(this).width();
  $(this).children('a').css("width", $currentWidth);
});

Upvotes: 1

Octopus
Octopus

Reputation: 8325

How about:

$('#your-ul').find('li.block').each(function(){
  // inside here, 'this' refers to to a specific 'li.block' element
  $(this).find('a').width( $(this).width() );
});

although I am a bit suspicious about why these aren't already the same width.

Upvotes: 0

Related Questions