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)

9
  • 1
    I'm sure this has been asked many times before. Why add another question and answer? Commented Jul 24, 2012 at 20:01
  • HUH? Why ask a question then post an Answer right away? Commented Jul 24, 2012 at 20:02
  • 1
    @Wirey: blog.stackoverflow.com/2011/07/… @ 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. Commented Jul 24, 2012 at 20:02
  • possible duplicate of Get an element by index in jquery or this... How to get a specific jQuery item from a list of items? Commented Jul 24, 2012 at 20:03
  • 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 Commented Jul 24, 2012 at 20:04

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.