cbp cbp - 14 days ago 4x
jQuery Question

How to 'pop' or 'shift' from jQuery set

In Javascript, arrays should have methods pop and shift.

However, JQuery objects seem to be missing these methods:

$('div').shift(); // Error, shift is undefined
$('div').pop(); // Error, pop is undefined
$('div').splice(); // Splice is OK actually

I wonder why these functions are missing - after all, the jquery object is just an array.

What's the easiest way of performing pop and shift functions on jquery objects?


They're missing because a jQuery object 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 object. Fixed to use .splice() instead.