7

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

3 Answers 3

13

Use eq :

$('#container li').eq(i)
answered Jan 18, 2013 at 21:32
Sign up to request clarification or add additional context in comments.

1 Comment

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.
7

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

Comments

0

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.