0

Possible Duplicate:
How to get nth jQuery element
Get an element by index in jquery

What is the jQuery equivalent of the square brackets [ ] indexing notation for selecting the Nth item from an array?

Say you have 10 paragraphs and want to get the contents of the 7th one. Using square bracket notation works, but not if you want to keep using jQuery:

$("p")[6];        //returns DOM object: [object HTMLParagraphElement]
$("p")[6].html(); //returns error: (Chrome:) Uncaught TypeError: Object #<HTMLParagraphElement> has no method 'html' (Firefox:) TypeError: $("p")[6].html is not a function (IE8+:) TypeError: Object doesn't support this property or method (IE7:) [object Error]

(jsfiddle example)

Community
  • 1
  • 1
brentonstrine
  • 21,694
  • 25
  • 74
  • 120
  • 1
    I'm sure this has been asked many times before. Why add another question and answer? –  Jul 24 '12 at 20:01
  • HUH? Why ask a question then post an Answer right away? – wirey00 Jul 24 '12 at 20:02
  • 1
    @Wirey: http://blog.stackoverflow.com/2011/07/its-ok-to-ask-and-answer-your-own-questions/ @ am no i am: I just spent a good amount of time trying to figure this out and many searches to stack overflow didn't bring up a question that answered this directly. – brentonstrine Jul 24 '12 at 20:02
  • possible duplicate of [Get an element by index in jquery](http://stackoverflow.com/questions/9887534/get-an-element-by-index-in-jquery) or this... [How to get a specific jQuery item from a list of items?](http://stackoverflow.com/questions/7514448/how-to-get-a-specific-jquery-item-from-a-list-of-items) –  Jul 24 '12 at 20:03
  • @wirey, brentonstrine: It's fine to ask and answer your own question, but not if it's a dupe. –  Jul 24 '12 at 20:03
  • That's what I meant. This question has been asked/answered so many times already – wirey00 Jul 24 '12 at 20:04
  • 4
    but this isn't anything new, this question has been asked and answered many many times before. It's not like you are providing the community some new, novel information, you're just wasting time and space – MrOBrian Jul 24 '12 at 20:04
  • I see the link there, somehow it didn't come up in my searches--probably because I didn't know enough about what I was asking to use the right keywords. I tried to craft this question so that the keywords would bring it up, but I see that it is indeed a duplicate. Sorry! – brentonstrine Jul 24 '12 at 20:05
  • You can delete it you know... – gdoron Nov 04 '13 at 09:06

1 Answers1

2

Square bracket [n] index notation works but you get the native Javascript DOM object, not something that jQuery can work with. Use jQuery's .eq() method or the :eq() selector to get a jQuery object.

$("p").eq(6).html();
$("p:eq(6)").html();

(jsfiddle example)

brentonstrine
  • 21,694
  • 25
  • 74
  • 120