jQuery: access original selection inside .each()?

Something I was wanting to do with jQuery the other day was to obtain a reference to the original selector from inside the each function. I was looking through the documentation and for the life of me couldn’t come across a suitable solution.

I had to use an external variable instead and reference that from within the function, which seems to be a non-optimal solution.

$('li').each(function () {
    // how to reference the $('li') selector from in here
    // without explicitly repeating the selector itself.

@pmw57, that is an interesting problem, although it doesn’t come up terribly often (most times you want the current element in the selection, not the entire selection). I think using an external variable isn’t really non-optimal, though. It’s one extra line of code, and doesn’t impact performance:

$li = $('li');
$li.each(function() {
  // $(this) is the current element and
  // $li is the full selection

What I was working on is a way to shuffle some list items.

The working code is:

$(function () {
    var items = '#slider ul li';
    var newItems = $('<ul></ul>');
    $(items).each(function (i) {
        var randomItem = Math.floor(Math.random() * ($(items).length - i));
    $('#slider ul').replaceWith($(newItems));

What I’m looking for is a way to refer to $(items) without doing so explicitly from within the function. Either by using built-in jQuery methods to gain the reference, or by passing it through in some manner.

I don’t think there’s any jQuery sugar for that, but you should probably store the result of the selection (as I did in my previous post), rather than the selector string. Running the same selection over and over like that will hurt performance.

The reason why the selection has to be run over again, is that each time through the list itself changes due to one of the list items being moved out to the new items.

I suspect though that there are better ways?

I guess you do need to keep a refreshed copy of the object with each iteration. Even with standard DOM methods you would need to keep accessing childNodes (or something similar), as a NodeList obtained via getElementsByTagName(‘li’) would still be static.