1

Theoretically speaking, if I had a list of unordered items

<ul>
    <li><a>Link1</a></li>
    <li><a>Link1</a></li>
</ul>

How I could do the following with jQuery?

1) Find the width of each individual a element

2) Find the width of each individual li element

3) Subtract the width of each child a element from the width of it's parent li element

4) Then add the total to each parent li element

This doesn't work:

$('ul > li').each(function() {
  var liWidth = (this).width();
  var aWidth = ('ul > li > a').width();
  var subractedWidth = parseFloat(liWidth) - parseFloat(aWidth);
  var newWidth = subtractedWidth + parseFloat(liWidth);
  $(this).css('width',newWidth);  
});

Thanks in advance!

1
  • and $('ul > li > a) note ('ul > li > a)
    – Zevan
    May 27, 2012 at 0:27

3 Answers 3

2

You forgot to use the $ in a few spots, and you are trying to get the <a> width that is within the specific <li> you are in, so you shouldn't requery the entire DOM. This would do it:

$('ul > li').each(function() {
    var liWidth = parseFloat($(this).width());
    var aWidth = parseFloat($(this).find('a').eq(0).width());
    $(this).width((liWidth - aWidth) + liWidth);
});
1
  • Thanks again for help with the syntax
    – dcd0181
    May 27, 2012 at 0:59
1

You could do

$('ul > li > a').each(function () {
    var li = $(this).closest('li'), 
        liWidth = li.width(),
        aWidth = $(this).width();

    li.width(liWidth + (liWidth - aWidth));
});
0

Looks like you forgot some $.

$('ul > li').each(function() {
  var liWidth = $(this).width();
  var aWidth = $(this).find('a').width();
  var subractedWidth = parseFloat(liWidth) - parseFloat(aWidth);
  var newWidth = subtractedWidth + parseFloat(liWidth);
  $(this).css('width',newWidth);  
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.