3

I have a JS function that returns a list of ".youtube" elements, loops through the selector, and calls another function. The JavaScript function is working beautifully, but I want to translate it into jQuery. Here's the JS function, which works correctly:

var videos = document.querySelectorAll(".youtube");
for (var i = 0; i < videos.length; i++) {
    getVideos(videos[i]);
}

Now here's my attempt at translating it into jQuery:

$(".youtube").each(function(i, youtube){
    getVideos(youtube[i]);
});

This doesn't work. Here's a JSFiddle: http://jsfiddle.net/k3y3yvxq/2/

2 Answers 2

5

No need for index in jQuery each(), youtube refers to the element

The .each() method is designed to make DOM looping constructs concise and less error-prone. When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0. More importantly, the callback is fired in the context of the current DOM element, so the keyword this refers to the element. ( Taken from https://api.jquery.com/each/ )

$(".youtube").each(function(i, youtube){
    getVideos(youtube);
    // or getVideos(this);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Duh. I feel stupid now. I'll accept when timer runs out.
3

You can also do it like this:

$(".youtube").get().forEach(getVideos);

...provided getVideos only looks at its first argument and not subsequent ones, as it will get called with three arguments: The element, its index, and the array we're looping over (which is what .get() gives us, a true JavaScript array).

Or the "less jQuery" way:

Array.prototype.forEach.call(document.querySelectorAll(".youtube"), getVideos);

I should note that forEach is ES5+ (e.g., circa 2009), so IE8 doesn't have it, as IE8 was released before the ES5 specification was finalized. All modern browsers do.

1 Comment

This is a very elegant solution, thanks for your input.

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.