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/

3 Answers 3

13

Use eq :

$('#container li').eq(i)
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.

Comments

0

You can also do something like this using nth-child:

$("#container li:nth-child(1)").width(); // first li

Comments

Your Answer

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.