Reputation: 6540
This is my first jQuery code. I want my ul element with class ".topnav" to have value of width attribute from the most width attribute li element that it contains. I have code like this and css for li elements display:none
:
$(function(){
$('.topnav').each(function(){
$(this).attr('width', Math.max($(this).children().each(function(){$(this).attr('width')})))});
})
But it isn't work. Does someone could help?
Upvotes: 0
Views: 201
Reputation: 17844
Hmm, it's hard to understand your question. Did you mean, you want your ul's width to be the same as the widest li? If so, do you want to include the padding/border/margin of the li?
Instead of using attr('width'), use width([value]) or outerWidth([value]) to get/set your width.
A lot of other mistake in the code, your $(this).children().each
does not return the width. Hang on, let me whip something out real quick, plz hold.
Here you go:
var maxWidth = Math.max.apply(Math, $('.topnav > li').map(function(){ return $(this).width(); }).get());
$('.topnav').width(maxWidth);
The map
function 'converts' the array of li into an array of its width. get
converts it into regular Javascript array. Then you apply the function max
passing it Math
as the scope in the first argument and the array in the second argument.
Upvotes: 2
Reputation: 6127
var maxwidth = 0;
$('.topnav').each(function(){
$(this).children().each(function(){
if($(this).width() > maxwidth){
maxwidth = $(this).width();
}
});
});
Then you would set the width of .topnav
to maxwidth
.
Upvotes: 0