admin管理员组

文章数量:1426058

I am having an annoying bug that I forgot why it happens:

I have an ordinary html list

<ul> <li>Some text</li> <li>Another Text </li> <li>text</li> <li>another one</li> </ul>

and I am trying to measure each li width

I was trying to write this jQuery code:

for (var i=0; i++; i <4)
{
   $("ul li")[i].width();
}

but somehow that doesn't work - what am I doing wrong in this sentence $("ul li")[i].width(); ?

I am having an annoying bug that I forgot why it happens:

I have an ordinary html list

<ul> <li>Some text</li> <li>Another Text </li> <li>text</li> <li>another one</li> </ul>

and I am trying to measure each li width

I was trying to write this jQuery code:

for (var i=0; i++; i <4)
{
   $("ul li")[i].width();
}

but somehow that doesn't work - what am I doing wrong in this sentence $("ul li")[i].width(); ?

Share Improve this question edited Nov 30, 2011 at 14:03 user212218 asked Nov 28, 2011 at 13:21 AlonAlon 7,75820 gold badges64 silver badges100 bronze badges 3
  • what do you expect to happen? – Alessandro Pezzato Commented Nov 28, 2011 at 13:23
  • what is it that you are expecting? – Arindam Commented Nov 28, 2011 at 13:23
  • I want to check the width of each <li> element - assuming each one has different text size – Alon Commented Nov 28, 2011 at 13:23
Add a ment  | 

6 Answers 6

Reset to default 3
$('ul li').each(function(){
     /*width*/
     console.log( $(this).width());
     /*width+padding*/
     console.log( $(this).outerWidth(true));
});
$('ul li').each(function()
{
    $(this).width();
});

This is far more simple to walk over a set of elements with the .each() function.

For use in a custom loop, you need to use the .eq() method (and you should cache the list of element, instead of re-searching for all of them)

var li_elements = $("ul li");
for(var i=0, len = li_elements.length; i<len; i++) {
  var elementWidth = li_elements.eq(i).width();
   // do what you need with it..
}

or you can use the .each() to iterate over the list

$("ul li").each(function(){
   var elementWidth = $(this).width();
   // do what you need with it..
})

$("ul li")[i] is returning you a DOM element, not a jQuery object. Use:

var elements = $("ul li");
elements.each(function(){
    //do something with $(this).width()
});

Note also, using the selector once outside the loop and them iterating over it, rather than repeating the selection every time.

When you use an indexer with a jquery object, you get the DOM elements.

try:

var $items = $("ul li");
for (var i=0; i < 4; i++)
{
   $items.eq(i).width();
}

Accessing array items on jQuery objects will return you the actual DOM object, not the one wrapped with jQuery's sugar. Use $(...).eq(0).width() instead.

Also, you can just use the each() method to iterate over all the items instead of a for loop, which is much easier, nicer-looking and elegant IMHO.

本文标签: javascriptHow to measure an elements width with jQueryStack Overflow