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?
pop = function() { var top = this. get(-1); this. splice(this. length-1,1); return top; }; $.
$ sign is just a valid javascript identifier which is used as an alias for jQuery. Prototype, jQuery, and most javascript libraries use the $ as the primary base object (or function). Most of them also have a way to relinquish the $ so that it can be used with another library that uses it.
All you have to do is select the element(s) you want to move, then call an “adding” method such as append() , appendTo() or prepend() to add the selected elements to another parent element. jQuery automatically realises that the element(s) to add already exist in the page, and it moves the element(s) to the new parent.
shift() The shift() method removes the first element from an array and returns that removed element.
They're missing because a jQuery object isn't an Array.
(function( $ ) { $.fn.pop = function() { var top = this.get(-1); this.splice(this.length-1,1); return top; }; $.fn.shift = function() { var bottom = this.get(0); this.splice(0,1); return bottom; }; })( jQuery );
EDIT: .slice()
doesn't modify the original object. Fixed to use .splice()
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With