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?

3 Answers 3

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.

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

4 Comments

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?
I have no idea what you've seen.
stackoverflow.com/questions/2988050/…. Look for the response by @edwardsharp
@webDev an <audio> DOM element has a .play() method natively, no jQuery or anything else
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.

3 Comments

can you take a look at the question I asked @Amit in the comment section ?
An <audio> element contains the methods on this page as part of it's native interface: developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement
@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.
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.

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.