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?
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().eachdoes not return the width. Hang on, let me whip something out real quick, plz hold.Here you go:
The
mapfunction ‘converts’ the array of li into an array of its width.getconverts it into regular Javascript array. Then you apply the functionmaxpassing itMathas the scope in the first argument and the array in the second argument.