I need to be able to get the width of elements from an array
HTML
<div id="container">
<ul>
<li id="one">--------</li><br />
<li id="two">----------------</li><br />
<li id="three">-------</li><br />
</ul>
</div>
JS
I know i can access the individual width's like this
$('#one').width();
But in an array
var $array = $("#container li");
How do i access a specific width of the element by its index
e.g
$array[2].width(); //which causes error
Example http://jsfiddle.net/8zvkn/
asked Jan 18, 2013 at 21:30
eleven11
3622 gold badges3 silver badges12 bronze badges
3 Answers 3
Use eq :
$('#container li').eq(i)
answered Jan 18, 2013 at 21:32
Denys Séguret
384k90 gold badges813 silver badges780 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Mike Brant
Yes the problem with OP oringal attempt using
$array[2]. Is that $array[2] is a DOM element not a jQuery object, so you can't perform width() on it. Using eq() you get a filtered jQuery object for the element at that index.You can use .eq function like below,
$array.eq(2).width()
DEMO: http://jsfiddle.net/8zvkn/2/
$array[2] - returns DOM element but what you need is the jQuery object which has the .width function.
answered Jan 18, 2013 at 21:32
Selvakumar Arumugam
79.9k15 gold badges123 silver badges139 bronze badges
Comments
You can also do something like this using nth-child:
$("#container li:nth-child(1)").width(); // first li
answered Jan 18, 2013 at 21:45
insomiac
5,6848 gold badges47 silver badges73 bronze badges
Comments
lang-js