webDev
webDev

Reputation: 109

Chaining methods to returned JQuery objects

While trying to get a better understanding of JQuery I came across this question

What I got from it was the JQuery selector returns an array-like structure that you can iterate over like an array. My question is under what circumstances can I do something like this:

  $('.foo')[1].someFunction();

without causing the error: $(...)[1].someFunction is not a function (someFunction refers to a defined JQuery function like appendTo()or text()) .

Also why will it cause an error and whats the best method (if possible) of chaining a function after using [] notation?

Upvotes: 2

Views: 51

Answers (3)

Josh Rumbut
Josh Rumbut

Reputation: 2710

You could do something like $('.foo').first() or $('.foo').eq(1), which is the more idiomatic way to access the results of a jQuery selector.

As @Amit notes, the objects in the underlying array structure are native DOM elements. A silly but perhaps instructive way to use them in a jQuery method chain would be $($('.foo')[1]).whatever()

Getting at the questions asked in comments, native DOM elements have their own (rather large) set of methods that can be called on them. For instance, all HTML Elements have this very much worth knowing interface available, and every specific kind of element has it's own extensions of this.

Upvotes: 2

SimianAngel
SimianAngel

Reputation: 629

When you access a jQuery object with an array selector, the DOM element is returned. As it's no longer a jQuery object, it will no longer have access to jQuery's methods and properties.

You could try using something like $('.foo').eq(1) and then chain jQuery methods off of that.

Upvotes: 1

Amit
Amit

Reputation: 46323

under what circumstances can I do something like this:

$('.foo')[1].someFunction();

Under no circumstances. The objects in the "array" are the native DOM objects, they don't support jQuery functions.

Upvotes: 3

Related Questions