2

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?

Community
  • 1
  • 1
webDev
  • 109
  • 9

3 Answers3

3

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.

Amit
  • 45,440
  • 9
  • 78
  • 110
  • I've seen people do something like this: `$('.foo')[0].play()` and it work. I know that `play()` is a js function. Is that why it works? – webDev May 20 '16 at 18:13
  • I have no idea what you've seen. – Amit May 20 '16 at 18:16
  • http://stackoverflow.com/questions/2988050/html5-audio-player-jquery-toggle-click-play-pause. Look for the response by @edwardsharp – webDev May 20 '16 at 18:24
  • @webDev an ` – Josh Rumbut May 20 '16 at 18:35
2

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.

Josh Rumbut
  • 2,640
  • 2
  • 32
  • 43
  • can you take a look at the question I asked @Amit in the comment section ? – webDev May 20 '16 at 18:30
  • An – Josh Rumbut May 20 '16 at 18:34
  • @webDev added more documentation to my answer. That whole site is a tremendous resource for really gaining an understanding of HTML/CSS/JS, how they interact, and what you can and can't do. – Josh Rumbut May 20 '16 at 18:40
1

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.

SimianAngel
  • 631
  • 10
  • 14