Reputation: 1503
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!
Upvotes: 1
Views: 777
Reputation: 1666
You could do
$('ul > li > a').each(function () {
var li = $(this).closest('li'),
liWidth = li.width(),
aWidth = $(this).width();
li.width(liWidth + (liWidth - aWidth));
});
Upvotes: 1
Reputation: 933
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);
});
Upvotes: 0
Reputation: 488374
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);
});
Upvotes: 2