[ACCEPTED]-How to 'pop' or 'shift' from jQuery set-jquery

Accepted answer
Score: 41

They're missing because a jQuery object 2 isn't an Array.

(function( $ ) {
    $.fn.pop = function() {
        var top = this.get(-1);
        return top;

    $.fn.shift = function() {
        var bottom = this.get(0);
        return bottom;
})( jQuery );

EDIT: .slice() doesn't modify the original 1 object. Fixed to use .splice() instead.

Score: 15

Your safest bet would be to just use:


If 8 you want to use the exact syntax in your 7 example you can augment jQuery.fn:

jQuery.fn.pop = [].pop;
jQuery.fn.shift = [].shift;

The latter works 6 well for the mutator methods. It'll work for the accessor and iteration methods 5 too, but be advised that many of those returns 4 a pure array that you'd have to rewrap. Be 3 aware that jQuery has is own version of 2 some of these (e.g. .map, .slice, .filter, etc.) that you 1 probably don't want to overwrite.

Score: 7

This seemed to work for me:

var divArray = $('div').toArray();
var elem = $( divArray.shift() );

.toArray() return the DOM 3 elements as a JavaScript Array, which can 2 be used as intended. Then all you need to 1 do is convert it back into a jQuery object.

Score: 1

I realize this answer has already been selected, but 6 here's another alternative that isn't too 5 hard to remember, in case you don't want 4 to worry about having to install plugins 3 all the time.

$('div > :first').detach(); // shift
$('div > :last').detach();  // pop

By the way, I realize there 2 are performance issues with using :last selector as part of your primary selector so you may want to consider doing something 1 like this for pop:

Score: 0
var $firstDiv = $( $('div').splice(0, 1) );


More Related questions